Elasticsearch过滤嵌套字段仅返回数组匹配对象的方法
该需求可以在Elasticsearch中实现。你当前的查询只能筛选出符合条件的父文档,是因为默认返回的_source是文档写入时的原始存储内容,普通嵌套查询的过滤逻辑不会自动修改原始_source里的嵌套数组内容,需要借助特定参数实现元素级别的返回过滤。
首先必须确保索引mapping中groupInfo字段被声明为nested类型,如果使用默认的object类型,ES会将数组内的字段扁平化存储,无法实现嵌套对象的独立匹配与过滤。正确的mapping配置片段如下:
PUT /my_index { "mappings": { "request": { "properties": { "basicInfo": { "properties": { "requestId": {"type": "integer"} } }, "managerInfo": { "properties": { "manager": {"type": "keyword"} } }, "groupInfo": { "type": "nested", "properties": { "id": {"type": "keyword"}, "name": {"type": "keyword"}, "status": {"type": "keyword"} } } } } } }
方案1:通过nested的inner_hits实现(推荐,性能最优)
inner_hits是Elasticsearch为嵌套文档、父子文档设计的原生特性,专门用于返回匹配查询条件的子文档片段,是官方推荐的实现方式,只需要对你原有查询做两处调整:
- 在顶层
_source配置中排除全量groupInfo字段,避免返回不匹配的数组元素 - 在
nested查询块中添加inner_hits配置,声明返回符合条件的嵌套对象
最终查询语句如下:
{ "_source": { "excludes": ["groupInfo"] }, "query": { "bool": { "must": [ { "term": { "basicInfo.requestId": 123 } }, { "nested": { "path": "groupInfo", "query": { "term": { "groupInfo.status": "Approved" } }, "inner_hits": { "_source": true, "size": 100 } } } ] } } }
返回结果中,每个命中的父文档会新增inner_hits节点,其中groupInfo.hits.hits下的_source就是所有状态为Approved的嵌套对象,你只需要在业务代码中把这部分内容提取出来,拼回父文档的_source结构即可,不需要遍历全量数组做过滤。
返回结构核心片段参考:
{ "hits": { "hits": [ { "_index": "my_index", "_type": "request", "_id": "123", "_score": 3.0602708, "_source": { "basicInfo": {"requestId": 123}, "managerInfo": {"manager": "John"} }, "inner_hits": { "groupInfo": { "hits": { "hits": [ { "_source": { "id": "id1", "name": "abc", "status": "Approved" } } ] } } } } ] } }
方案2:通过script_fields直接返回过滤后的数组(无需业务层拼接)
如果你不想在业务层做结果拼接,希望ES直接返回结构完全符合预期的结果,可以使用Painless脚本遍历原始_source的嵌套数组,过滤出符合条件的元素返回。注意脚本执行性能弱于原生inner_hits方案,数据量较大时不推荐使用。
查询语句如下:
{ "_source": { "excludes": ["groupInfo"] }, "query": { "bool": { "must": [ {"term": {"basicInfo.requestId": 123}}, { "nested": { "path": "groupInfo", "query": {"term": {"groupInfo.status": "Approved"}} } } ] } }, "script_fields": { "groupInfo": { "script": { "lang": "painless", "source": """ def matched = []; for (def item : params._source.groupInfo) { if (item.status == 'Approved') { matched.add(item); } } return matched; """ } } } }
该查询返回的fields.groupInfo字段就是过滤完成、仅包含Approved状态对象的数组,结构和你预期的返回结果完全一致。
- 不要尝试仅通过
_source的includes/excludes规则过滤嵌套数组元素,该规则只能控制字段是否返回,不支持数组元素级别的条件判断。 - 如果
basicInfo.requestId是整数类型,查询时直接传数字值即可,不需要用字符串+match查询,用term查询性能更高。
内容的提问来源于stack exchange,提问作者neha pasbola

