2

我在elasticsearch中有这样的查询:

"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. 正确的方法是什么?非常感谢。

4

1 回答 1

14

你快到了,你搞砸了一个括号。但是,让我们用更易读的代码重写您的查询:

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);
于 2016-12-02T06:06:51.263 回答