elasticsearch ES查询以匹配数组中的所有元素
所以我用一个 要使用此查询筛选的嵌套数组 我希望ES返回所有项目更改为0且仅为0的所有文档。 如果文档在列表中有一个项的更改=1,则该项将被丢弃 从我已经编写的查询开始,有什么方法可以实现这一点吗?或者我应该使用脚本来代替 文件:elasticsearch ES查询以匹配数组中的所有元素,elasticsearch,kibana,elastic-stack,kibana-7,elasticsearch,Kibana,Elastic Stack,Kibana 7,所以我用一个 要使用此查询筛选的嵌套数组 我希望ES返回所有项目更改为0且仅为0的所有文档。 如果文档在列表中有一个项的更改=1,则该项将被丢弃 从我已经编写的查询开始,有什么方法可以实现这一点吗?或者我应该使用脚本来代替 文件: { "id": "abc", "_source" : { "trips" : [ { "t
{
"id": "abc",
"_source" : {
"trips" : [
{
"type" : "home",
"changes" : 0
},
{
"type" : "home",
"changes" : 1
}
]
}
},
{
"id": "def",
"_source" : {
"trips" : [
{
"type" : "home",
"changes" : 0
},
{
"type" : "home",
"changes" : 0
}
]
}
}
查询:
GET trips_solutions/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"id": {
"value": "abc"
}
}
},
{
"nested": {
"path": "trips",
"query": {
"range": {
"trips.changes": {
"gt": -1,
"lt": 1
}
}
}
}
}
]
}
}
}
预期结果:
{
"id": "def",
"_source" : {
"trips" : [
{
"type" : "home",
"changes" : 0
},
{
"type" : "home",
"changes" : 0
}
]
}
}
Elasticsearch版本:7.6.2
已经阅读了这些答案,但它们没有帮助我:
首先,如果您按
id:abc
进行筛选,您显然无法返回id:def
其次,由于嵌套的字段被视为单独的子文档,因此您无法查询更改等于0的所有行程
——各个行程之间的连接丢失,它们“互不了解”
您可以使用internal\u hits
,只返回与嵌套查询匹配的行程:
GET trips_solutions/_search
{
"_source": "false",
"query": {
"bool": {
"must": [
{
"nested": {
"inner_hits": {},
"path": "trips",
"query": {
"term": {
"trips.changes": {
"value": 0
}
}
}
}
}
]
}
}
}
然后,最简单的解决方案是在父对象上动态保存此嵌套信息,并在生成的数组上使用范围/术语查询
编辑:
以下是如何在文档的顶层使用:
PUT trips_solutions
{
"mappings": {
"properties": {
"trips_changes": {
"type": "integer"
},
"trips": {
"type": "nested",
"properties": {
"changes": {
"type": "integer",
"copy_to": "trips_changes"
}
}
}
}
}
}
trips\u changes
将是一个数字数组——我假定它们是整数,但是
然后同步几个文档:
POST trips_solutions/_doc
{"trips":[{"type":"home","changes":0},{"type":"home","changes":1}]}
POST trips_solutions/_doc
{"trips":[{"type":"home","changes":0},{"type":"home","changes":0}]}
最后查询:
GET trips_solutions/_search
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "trips",
"query": {
"term": {
"trips.changes": {
"value": 0
}
}
}
}
},
{
"script": {
"script": {
"source": "doc.trips_changes.stream().filter(val -> val != 0).count() == 0"
}
}
}
]
}
}
}
请注意,我们首先通常使用嵌套的术语查询进行筛选,以缩小搜索上下文的范围(脚本速度较慢,因此这很有用)。然后,我们检查累积的顶级更改中是否存在任何非零的更改
,并拒绝适用的更改。感谢您的友好回复!不幸的是,这不是最适合我需要的选择!我需要过滤每一项,因为数组对我来说就像一个“包”,所以如果“包”不适合所有条件,我想丢弃文档。你知道脚本是否能帮我吗?更新了我的答案——希望能有帮助。非常感谢乔!你真是太好了!没问题!请随意接受并投票表决答案;)