You need to enable JavaScript to run this app. Elasticsearch多层嵌套查询如何仅返回匹配的嵌套路径数据
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch多层嵌套查询如何仅返回匹配的嵌套路径数据

解决方案

Elasticsearch的nested查询默认返回符合条件的完整文档_source,不会自动过滤未匹配的嵌套数组元素。要实现仅返回匹配的嵌套对象,需要在第二层嵌套查询中添加inner_hits配置,同时可以选择关闭原始_source的返回避免冗余。

调整后的查询语句

GET /drivers/_search
{
  "_source": false, 
  "query": {
    "nested": {
      "path": "driver",
      "query": {
        "nested": {
          "path": "driver.vehicle",
          "query": {
            "bool": {
              "must": [
                { "match": { "driver.vehicle.make": "Powell Motors" } },
                { "match": { "driver.vehicle.model": "Canyonero" } }
              ]
            }
          },
          "inner_hits": {} 
        }
      }
    }
  }
}

返回结果说明

调整后返回结果会新增inner_hits字段,里面仅包含匹配的vehicle对象,示例如下:

{
  "took" : 5,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 3.7349272,
    "hits" : [
      {
        "_index" : "drivers",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 3.7349272,
        "inner_hits" : {
          "driver.vehicle" : {
            "hits" : {
              "total" : {
                "value" : 1,
                "relation" : "eq"
              },
              "max_score" : 3.7349272,
              "hits" : [
                {
                  "_nested" : {
                    "field" : "driver",
                    "offset" : 0,
                    "_nested" : {
                      "field" : "vehicle",
                      "offset" : 0
                    }
                  },
                  "_score" : 3.7349272,
                  "_source" : {
                    "make" : "Powell Motors",
                    "model" : "Canyonero"
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
}

补充说明

  • 如果需要同时保留文档其他字段(比如driver.last_name),可以把_source设置为你需要返回的字段列表,例如"_source": ["driver.last_name"]
  • inner_hits支持额外配置,比如分页、排序等,可根据业务需求调整参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 18:54:05