2015-08-28 24 views
2

我试图创建一个查询/过滤器匹配文档只有当满足若干条件对同一个项目的数组。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}}, 
     ] }} 
    ] 
} 

任何想法线的东西怎么办? 感谢

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

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

编辑:它看起来像我需要做一个嵌套的存在过滤器来检查嵌套对象内的字段存在。 类似:

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

编辑: 哎呀 - 现在的亮点不工作了:

"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" : {}}, 
     ] 
    } 
} 

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

回答

4

您需要设置arr字段的类型nested这样的:

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

然后你需要使用一个nested query

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

exists过滤器需要指定完整的田间小路

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

不错。如何在嵌套数组上执行“存在”过滤器?它似乎没有工作了。只是过滤“存在”:{“field”:“arr”}现在不返回文档。 –

+0

请用您的实际查询 – Val

+0

更新您的问题。即使所有的文档都有,“arr”上的简单存在过滤器也不会返回任何内容。 –