Elasticsearch查询如何仅返回nested字段中符合条件的内层数据
解决方案
核心逻辑:你当前的查询已经配置了inner_hits,它本身就会返回匹配nested查询条件的嵌套对象,之所以还能看到所有inventory内容,是因为ES默认返回完整的原始文档_source,不会自动过滤_source里的nested字段内容,只需在查询中排除原始inventory字段即可。
修改后的完整查询语句如下:
{ "_source": { "excludes": ["inventory"] }, "query": { "bool": { "must": [ { "multi_match": { "fields": [ "description" ], "minimum_should_match": "75%", "operator": "and", "query": "rose", "type": "phrase_prefix" } }, { "nested": { "path": "inventory", "query": { "term": { "inventory.branch": "1" } }, "inner_hits": {} } } ] } } }
返回结果说明
修改后返回的每个命中文档会包含两部分内容:
- 除
inventory外的所有原始主文档字段,productid、description等字段会正常返回 - 新增
inner_hits.inventory字段,其中的hits数组就是仅符合inventory.branch=1条件的嵌套对象,不会包含任何不匹配的嵌套内容
如果需要保持原来的返回结构,直接在业务代码中把inner_hits.inventory.hits里的内容提取出来,赋值给inventory字段即可,ES本身不会主动修改原始存储的_source内容。
内容的提问来源于stack exchange,提问作者Come2Searcher
相关产品推荐
相关产品推荐

