You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch嵌套文档正确索引方法及符合业务需求的搜索请求构造

问题1解答:嵌套结构文档导入ES的正确方案

普通数组对象直接写入ES会被自动扁平化处理,丢失category和对应name的关联关系,因此必须按以下步骤处理:

  • 第一步:提前创建索引Mapping,将products字段设置为nested(嵌套)类型,这是ES保留嵌套对象关联关系的原生方案
  • 第二步:参考以下代码创建索引,由于题目说明分类和产品名称都是预定义枚举值,因此直接设置为keyword类型保证匹配精度:
PUT /enterprise_goods
{
  "mappings": {
    "properties": {
      "description": {
        "type": "text"
      },
      "products": {
        "type": "nested",
        "properties": {
          "category": {"type": "keyword"},
          "name": {"type": "keyword"}
        }
      }
    }
  }
}
  • 第三步:Mapping创建完成后,无需修改原有文档结构,直接调用单条写入API或者bulk批量API导入文档即可。
问题2解答:多条件检索请求编写

对应示例场景的完整查询DSL如下,逻辑完全匹配「description包含指定短语、有水果类产品、蔬菜类仅提供洋葱」的要求:

GET /enterprise_goods/_search
{
  "query": {
    "bool": {
      "must": [
        // 条件1:精确匹配description中的短语
        {
          "match_phrase": {
            "description": "South Africa"
          }
        },
        // 条件2:存在水果类产品
        {
          "nested": {
            "path": "products",
            "query": {
              "term": {"products.category": "fruits"}
            }
          }
        },
        // 条件3:蔬菜类包含洋葱
        {
          "nested": {
            "path": "products",
            "query": {
              "bool": {
                "must": [
                  {"term": {"products.category": "vegetables"}},
                  {"term": {"products.name": "onion"}}
                ]
              }
            }
          }
        }
      ],
      "must_not": [
        // 排除蔬菜类包含除洋葱外其他产品的结果,实现「仅提供洋葱」的要求
        {
          "nested": {
            "path": "products",
            "query": {
              "bool": {
                "must": [
                  {"term": {"products.category": "vegetables"}},
                  {"bool": {"must_not": {"term": {"products.name": "onion"}}}}
                ]
              }
            }
          }
        }
      ]
    }
  }
}

如果需要调整产品匹配规则,只需修改nested查询内的条件即可。

内容的提问来源于stack exchange,提问作者Andrei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:06:04