Elasticsearch如何过滤嵌套数组仅返回指定sub_attributes.id的对象?
解决方案
要实现仅返回嵌套数组中匹配指定ID的对象,你需要使用nested查询结合inner_hits——普通的terms查询只会筛选出包含目标ID的文档,但不会过滤嵌套数组内的无关元素,这就是你当前返回结果包含其他ID的原因。
假设你的sub_attributes字段是nested类型(若不是,需先将该字段设置为nested类型才能精准过滤嵌套元素),可使用以下查询:
{ "query": { "bool": { "must": [ { "nested": { "path": "sub_attributes", "query": { "terms": { "sub_attributes.id": [13, 15, 19] } }, "inner_hits": {} } } ] } } }
关键说明:
- nested查询:针对嵌套类型字段执行精准匹配,确保只定位到嵌套数组中符合条件的元素。
- inner_hits:指定单独返回匹配到的嵌套对象,查询结果会在
inner_hits字段下列出所有符合条件的sub_attributes条目,而非返回整个原数组。
若你的sub_attributes尚未设置为nested类型,需先修改索引映射:
PUT /your_index/_mapping { "properties": { "sub_attributes": { "type": "nested", "properties": { "id": { "type": "integer" }, // 此处添加sub_attributes的其他子字段定义 } } } }
补充:
如果不想通过inner_hits单独返回匹配结果,而是希望直接替换原字段数组为匹配元素,可通过应用层处理或使用脚本字段,但inner_hits是Elasticsearch原生支持的最直接方案。
内容的提问来源于stack exchange,提问作者Mohan T
相关产品推荐
相关产品推荐

