2014-11-03 54 views
0

我有一个关于使用应该和必须在布尔查询有点混淆。当SHOULD和MUST子句中有多个过滤器时,它们可以放在同一层次还是嵌套?布尔过滤器和应该和必须组合

下面是我的数据和我测试的两个查询的简化版本,第一个失败和后者工作。在实际的实践中,我必须有许多过滤器必须和应该。

我开始相信,如果你想结合几个SHOULD和MUST过滤器,外面的过滤器必须总是应该。这是一个正确的假设吗?如果我想使用MUST_NOT,那么它应该放在哪里?

我的数据:

_index,_type,_id,_score,_source.id,_source.type,_source.valueType,_source.sentence,_source.location 
"test","var","0","1","0","study","text","Lorem text is jumbled","spain" 
"test","var","1","1","1","study","text","bla bla bla","spain" 
"test","var","2","1","2","schema","decimal","ipsum","germany" 
"test","var","3","1","3","study","integer","lorem","france" 

这里是失败的查询:

{ 
    "query": { 
    "filtered": { 
     "query": { 
     "match_all": {} 
     }, 
     "filter": { 
     "bool": { 
      "must": { 
      "terms": { 
       "location": [ 
       "germany" 
       ] 
      } 
      }, 
      "should": { 
      "terms": { 
       "valueType": [ 
       "integer" 
       ] 
      } 
      } 
     } 
     } 
    } 
    } 
} 

这里是我工作的查询返回的ID 2和3:

{ 
    "query": { 
    "bool": { 
     "should": [ 
     { 
      "terms": { 
      "location": [ 
       "germany" 
      ] 
      } 
     }, 
     { 
      "bool": { 
      "must": [ 
       { 
       "terms": { 
        "valueType": [ 
        "integer" 
        ] 
       } 
       } 
      ] 
      } 
     } 
     ] 
    } 
    } 
} 

非常感谢。

回答

0

首先需要理解过滤器的含义。

复合过滤:

must条款要求(和)
should子句是可选的(或)

所以在第一块,您正在检查must(和)term。所以这个术语必须在结果集中。并应该(或)cond 2可能或不可以在结果集中。

{ 
    "query": { 
     "filtered": { 
     "query": { 
      "match_all": {} 
     }, 
     "filter": { 
      "bool": { 
       "must": { 
        ....... Cond 1 
       }, 
       "should": { 
        ....... Cond 2 
       } 
      } 
     } 
     } 
    } 
} 

在你的工作情况您查询工作,因为要检查条件1或2电导率

{ 
    "query": { 
     "bool": { 
     "should": [ // OR 
      { 
       ...... Cond 1 
      }, 
      { 
       ...... Cond 2 
      } 
     ] 
     } 
    } 
}