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

Gio*_*tti 6 elasticsearch

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

假设这是文档:

{
  arr: [
    { "f1" : "a" , f2 : true },
    { "f1" : "b" , f2 : false}
  ]
}
Run Code Online (Sandbox Code Playgroud)

我希望能够检索在同一元素上有 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}},
        ] }}
    ]
}
Run Code Online (Sandbox Code Playgroud)

知道该怎么做吗?谢谢

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

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

编辑:看起来我需要执行嵌套存在过滤器来检查嵌套对象内的字段是否存在。就像是:

"filter" : {
       "nested" : {"path" : "arr", "filter" : {"exists" : { "field" : "f1" } }}
}
Run Code Online (Sandbox Code Playgroud)

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

   "highlight" : {
        "fields" : [
            {"arr.f1" : {}},
        ]
    }
Run Code Online (Sandbox Code Playgroud)

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" : {}},
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Val*_*Val 5

您需要将字段的类型设置arrnested如下:

{
    "your_type": {
        "properties": {
            "arr": {
                "type": "nested",
                "properties": {
                    "f1": {"type":"string"},
                    "f2": {"type":"boolean"}
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你需要使用nested查询

{
    "nested" : {
        "path" : "arr",
        "query" : {
            "bool" : {
                "must" : [
                    {
                        "term" : {"arr.f1" : "a"}
                    },
                    {
                        "term" : {"arr.f2" : true}
                    }
                ]
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

"filter" : {
       "nested" : {"path" : "arr", "filter" : {"exists" : { "field" : "arr.f1" } }}
}
Run Code Online (Sandbox Code Playgroud)