2016-12-02 38 views
0

我有這樣的查詢中elasticsearch:如何在java api中的should/must方法中添加bool查詢?

"query": { 
     "bool": { 
      "should": [ 
      {"bool": { 
        "must": [ 
         {"term": { 
          "field1": "value1" 
         }}, 
         {"term": { 
          "field2": "value2" 
         }} 
       ]} 
       }, 
       {"bool": { 
        "should": [ 
         {"term":{     
          "field1": "value3" 
         }} 
       ]}  
       } 
      ] 
     } 
    } 

基本上,它是((field1 == value1 AND field2 == value2) OR (field1 == value3))。但是我還沒有找到在Java API中實現它的方法。我已經試過這樣的事情:

BoolQueryBuilder filter = new BoolQueryBuilder() 
        .should(QueryBuilders.termQuery(field1, value3) 
        .should(QueryBuilders.boolQuery().must(QueryBuilders.termQuery(field1, value1)) 
          .must(QueryBuilders.termQuery(field2, value2))) 
        ); 

should方法不採取BoolQueryBuilder。什麼是正確的方法來做到這一點?非常感謝你。

回答

0

你幾乎在那裏,你搞砸了一個括號。但讓我們用更易讀的代碼重寫您的查詢:

BoolQueryBuilder first = QueryBuilders.boolQuery() 
    .must(QueryBuilders.termQuery(field1, value1)) 
    .must(QueryBuilders.termQuery(field2, value2)); 

BoolQueryBuilder second = QueryBuilders.termQuery(field1, value3); 

BoolQueryBuilder filter = new BoolQueryBuilder() 
    .should(first) 
    .should(second); 
+0

如果我必須構建一個term term查詢並將它們添加到should(),該怎麼辦? – jagamot

+0

@jagamot迭代你的數組並用'.should()替換'.must()'' – Val