小编典典

Elasticsearch Bool过滤器用于数组同一元素上的多个条件

elasticsearch

我正在尝试创建仅在数组 的同一项目 上满足多个条件的情况下与文档匹配的查询/过滤器。

假设这是文档:

{
  arr: [
    { "f1" : "a" , f2 : true },
    { "f1" : "b" , f2 : false}
  ]
}

我希望能够检索在同一元素上具有N个条件匹配的文档。例如:arr.f1 == "a" AND arr.f2 == true应该匹配文档,但是arr.f1 == "b" AND arr.f2 == true不应该匹配。

我正在尝试嵌套布尔过滤器(除此过滤器之外,我还有其他过滤器),但是它不起作用,有些类似于

"bool" : {
    "must": [
        { some other filter },
        {"bool": {"must" : [
            {"term" : {"arr.f1" : "a"}},
            {"term" : {"arr.f2" : true}},
        ] }}
    ]
}

任何想法如何做到这一点?谢谢

编辑 :我更改了映射,现在嵌套查询根据Val的响应工作。我现在无法在嵌套字段上执行“存在”过滤器:

简单{ "filter" : {"exists" : { "field" : "arr" } } }搜索不会返回任何匹配。我怎么做?

编辑:看来我需要做一个嵌套的存在过滤器,以检查嵌套对象内的字段是否存在。就像是:

"filter" : {
       "nested" : {"path" : "arr", "filter" : {"exists" : { "field" : "f1" } }}
}

编辑:argh-现在突出显示不再起作用:

   "highlight" : {
        "fields" : [
            {"arr.f1" : {}},
        ]
    }

通过添加include_in_parent : true和查询嵌套字段和根对象来解决此问题。真可怕 如果有人有更好的主意,那就非常欢迎他们!

{   
    "query" : {
        "bool" : {
            "must": [
                {"term" : { "arr.f1" : "a" }},
                { "nested" : { "path" : "arr", 
                   "query" :  { "bool" : { "must" : [ 
                        {"term" : { "arr.f1" : "a" }},
                        {"term" : { "arr.f2" : true }}
                   ] } } 
                }}
            ]
        }
    },
    "highlight" : {
        "fields" : [
            {"arr.f1" : {}},
        ]
    }
}

如果您想知道:这是旧的东西。我现在无法重新编制索引(这将是显而易见的解决方案),并且我需要一种快速且肮脏的解决方法


阅读 383

收藏
2020-06-22

共1个答案

小编典典

您需要像下面这样设置arr字段的类型nested

{
    "your_type": {
        "properties": {
            "arr": {
                "type": "nested",
                "properties": {
                    "f1": {"type":"string"},
                    "f2": {"type":"boolean"}
                }
            }
        }
    }
}

然后,您需要使用nested查询

{
    "nested" : {
        "path" : "arr",
        "query" : {
            "bool" : {
                "must" : [
                    {
                        "term" : {"arr.f1" : "a"}
                    },
                    {
                        "term" : {"arr.f2" : true}
                    }
                ]
            }
        }
    }
}

您的exists过滤器需要指定完整的字段路径

"filter" : {
       "nested" : {"path" : "arr", "filter" : {"exists" : { "field" : "arr.f1" } }}
}
2020-06-22