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
相关产品推荐
相关产品推荐

