2014-11-03 80 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 
      } 
     ] 
     } 
    } 
}