How to add bool query inside a should/must method in java api?

tflave picture tflave · Dec 2, 2016 · Viewed 10.6k times · Source

I have a query like this in elasticsearch:

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

Basically, it's ((field1 == value1 AND field2 == value2) OR (field1 == value3)). But I have not found a way to implement that in the Java API. I have tried something like this:

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

but the should method doesn't take a BoolQueryBuilder. What's the correct way to do it? Thank you very much.

Answer

Val picture Val · Dec 2, 2016

You're almost there, you have messed up one parenthesis. But let's rewrite your query in a more readable code:

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);