[英]ElasticSearch: Filter for documents where any value in an array field is not in a list
I have a situation where I have field containing an array of integers. 我遇到的情况是我的字段包含整数数组。 I need to be able to implement a query that filters out documents that contain only a certain set of values in this array.
我需要能够实现一个查询,该查询可以过滤出仅包含此数组中的一组特定值的文档。
For example, say I created the following index: 例如,假设我创建了以下索引:
PUT /test/stuff/1
{
"foo": [1,2,3]
}
PUT /test/stuff/2
{
"foo": [2]
}
PUT /test/stuff/3
{
"foo": [1,3]
}
Now I would like to get all documents where "foo" contains any value that is not in [2,4]. 现在,我想获取所有文档,其中“ foo”包含不在[2,4]中的任何值。 I want to have the documents with ids 1 and 3 to be returned.
我想返回ID为1和3的文档。 Not that document 1 does contain the value
2
, but also contains other values. 并非该文档1确实包含值
2
,还包含其他值。 A simple must_not
like this will filter out document 1: 像这样的简单
must_not
会过滤掉文档1:
POST /test/stuff/_search
{
"query": {
"bool": {
"must" : {
"match_all": {}
},
"filter" : {
"bool": {
"must_not": [
{
"terms" : {"foo" : [2,4]}
}
]
}
}
}
}
}
The above query will only match document 3. Is there a way to rewrite this to also include document 1? 上面的查询将仅匹配文档3。是否可以重写此文档以使其也包含文档1?
This is doable with a script query, illustrated with painless as follows: 这是可行的一个脚本查询,以示无痛如下:
{
"query": {
"bool": {
"must" : {
"match_all": {}
},
"filter" : {
"bool": {
"must": {
"script" : {
"script" : {
"inline" : "for(int i: doc['foo']) { boolean matches = true; for(int j: params.param1){if(i==j) matches = false;} if(matches) return true;} ",
"lang" : "painless",
"params" : { "param1": [2,4]}
}
}
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.