Elasticsearch _search查询如何实现仅返回匹配指定字段值的内容
Elasticsearch 仅返回匹配内容的实现方案
你要的文档内容过滤效果,可按场景选择对应实现方式:
场景1:普通非嵌套文档,仅返回指定字段
直接通过_source参数配置即可实现SQL中select 字段的效果,示例:
{ "_source": ["field1", "field2"], "query": { // 你的查询条件 } }
不需要返回任何顶层字段的话,直接设置"_source": false即可。
场景2:包含nested嵌套字段,仅返回嵌套数组中匹配的条目
你当前的查询用到了嵌套查询,要过滤掉嵌套数组中不满足条件的条目,需要在nested查询中添加inner_hits参数,修改后的完整查询如下:
{ "_source": ["params"], "query": { "bool": { "must": [ { "match": { "params.show": true } }, { "nested": { "path": "childs", "query": { "nested": { "path": "childs.params", "query": { "bool": { "must": { "match": { "childs.params.show": true } } } } } }, "inner_hits": { // 可额外配置嵌套字段的返回内容,不需要的话留空即可 "_source": ["childs.name", "childs.params"] } } } ] } } }
返回结果中,匹配的嵌套条目会存放在hits.hits[].inner_hits.childs.hits路径下,不会返回整个childs数组,完全满足你只返回匹配内容的需求。
内容的提问来源于stack exchange,提问作者Marcsu
相关产品推荐
相关产品推荐

