gpt4 book ai didi

Elasticsearch 嵌套对象过滤器

转载 作者:行者123 更新时间:2023-11-29 02:52:26 27 4
gpt4 key购买 nike

我是 Elasticsearch 的新手,我正在尝试创建一个过滤器来检索具有特定属性的文档。

属性在映射中定义为嵌套对象,如下所示:

"attributes": {
"type": "nested",
"properties" : {
"id": {
"type": "integer"
},
...
}
}
}

我正在尝试执行以下形式的复杂查询:

(attribute.id == 1 OR attribute.id == 2) AND (attribute.id == 3 OR attribute.id == 4)

根据我到目前为止所读的内容,我创建了以下对 es 的查询:

{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"nested": {
"path": "attributes",
"filter": {
"bool": {
"must": [
{ "bool" : {
"should" : [
{ "term": { "attributes.id": 1 }},
{ "term": { "attributes.id": 2 }}
]
}},
{ "bool" : {
"should" : [
{ "term": { "attributes.id": 3 }},
{ "term": { "attributes.id": 4 }}
]
}}
]
}
}
}
}
}
},
"sort": {
"date": { "order": "desc" }
}
}

但是这不会返回任何结果。如果我删除 must block 中的两个 bools 之一,它会正确过滤文档。

如果我将查询(出于测试目的)更改为:

"must": [
{ "term": { "attributes.id": 3 }},
{ "bool" : {
"should" : [
{ "term": { "attributes.id": 1 }},
{ "term": { "attributes.id": 2 }}
]
}}
]

根据我的理解,它转换为 attributes.id == 3 AND (attributes.id == 1 OR attributes.id == 2)

这是 elasticsearch 2.x。我做错了什么?

最佳答案

为了获得您要查找的结果,您需要执行两个单独的嵌套 查询并将它们与一个bool 查询链接在一起。

这是一个例子:

{
"bool":{
"must":[
{
"nested":{
"path":"attributes",
"filter":{
"bool":{
"should":[
{ "term": {"attributes.id": 1 }},
{ "term": {"attributes.id": 2 }}
]
}
}
}
},
{
"nested":{
"path":"attributes",
"filter":{
"bool":{
"should":[
{ "term": {"attributes.id": 3 }},
{ "term": {"attributes.id": 4 }}
]
}
}
}
}
]
}
}

这是由于嵌套文档和嵌套查询的细微差别造成的。看看 documentation on nested queries 的部分上面写着:

The query is executed against the nested objects / docs as if they were indexed as separate docs (they are, internally) and resulting in the root parent doc (or parent nested mapping).

在执行嵌套 查询时,您实际上并不是在对根文档执行查询(尽管它感觉 是那样)。查询对嵌套文档进行操作,就好像它们是单独的文档一样

因此,当您查询具有两者 id=(1 或 2)和 id=(3 或 4)的嵌套文档时,您不会得到任何结果。在您的数据中,每个嵌套文档似乎只有这些 id 值之一。

关于Elasticsearch 嵌套对象过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34947195/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com