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

ElasticSearch嵌套查询求助:仅返回匹配的labels对象

如何在Elasticsearch中仅返回嵌套字段中匹配的对象

你需要正确配置inner_hits并关闭主文档的源数据返回,就能只拿到匹配的嵌套对象。以下是可行的查询语句:

GET /my-index/_search
{
  "query": {
    "nested": {
      "path": "labels",
      "query": {
        "match": {
          "labels.key": "us"
        }
      },
      "inner_hits": {
        "_source": ["labels.key", "labels.value"]
      }
    }
  },
  "_source": false
}

关键配置说明:

  • _source: false:关闭主文档的源数据返回,避免返回完整的title和所有labels对象
  • inner_hits._source:指定只返回嵌套对象中的key和value字段,精简结果

执行后,匹配的嵌套对象会出现在响应的hits.hits[].inner_hits.labels.hits.hits节点下,结构如下:

{
  "hits": {
    "hits": [
      {
        "_id": "你的文档ID",
        "_index": "my-index",
        "_score": 0.2876821,
        "inner_hits": {
          "labels": {
            "hits": {
              "hits": [
                {
                  "_source": {
                    "key": "region",
                    "value": "us-la"
                  },
                  "_score": 0.2876821
                }
              ]
            }
          }
        }
      }
    ]
  }
}

如果需要进一步精简输出,可以结合collapse或者script_fields,但上述方式是最直接满足需求的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:43:31