如何在Elastic Search中筛选仅含指定attributes.name值的文档?
在Elasticsearch中筛选仅包含指定attributes.name的文档
我在Elasticsearch中存储了3个结构如下的文档:
[ { "name": "Test_1", "attributes": [ { "name": "attribute_1" }, { "name": "attribute_2" } ] }, { "name": "Test_2", "attributes": [ { "name": "attribute_1" }, { "name": "attribute_2" }, { "name": "attribute_3" } ] }, { "name": "Test_3", "attributes": [ { "name": "attribute_2" }, { "name": "attribute_3" } ] } ]
需求:筛选出**仅包含attributes.name为attribute_1和attribute_2**的文档,最终仅返回Test_1,因为它恰好只包含这两个指定值,不多不少。
解决方案
使用布尔查询结合脚本筛选,确保文档同时满足以下条件:
- 包含所有指定的属性值
- 不包含任何指定之外的属性值
- 属性数量与指定的数量一致(避免重复属性的情况)
查询DSL如下:
{ "query": { "bool": { "must": [ {"term": {"attributes.name": "attribute_1"}}, {"term": {"attributes.name": "attribute_2"}} ], "filter": [ { "script": { "source": "def allowedAttrs = ['attribute_1', 'attribute_2']; doc['attributes.name'].every(attr -> allowedAttrs.contains(attr)) && doc['attributes.name'].size() == allowedAttrs.size()" } } ] } } }
逻辑说明
must子句:强制文档必须包含attribute_1和attribute_2这两个属性filter中的脚本:- 遍历文档所有
attributes.name,确保每个值都在允许的列表内 - 检查属性数量与允许的属性数量完全匹配,防止出现重复属性(比如两个
attribute_1)但总数量符合的情况
- 遍历文档所有
内容的提问来源于stack exchange,提问作者Disteonne
相关产品推荐
相关产品推荐

