2

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.

tflave
  • 58
  • 1
  • 2
  • 9

1 Answers1

16

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);
Val
  • 207,596
  • 13
  • 358
  • 360
  • What if I have to build build an array of term queries and add them to should()? – jagamot Feb 20 '18 at 04:41
  • @jagamot iterate over your array and replace `.must()` by `.should()` – Val Feb 20 '18 at 05:11
  • @Val i understand must is like AND operator, if i have an array, is it possible to do something like .must(arrayOfTermQueries)? – Catalina Feb 23 '22 at 08:42
  • @Catalina I suggest you create a new question describing your use case so you can get concrete answers – Val Feb 23 '22 at 08:42
  • will do it on demand, i think was looking for somehting like this https://stackoverflow.com/a/41606360/12541916 – Catalina Feb 23 '22 at 08:43
  • Then yes, use either must or filter and each element of your array should be a match/term clause – Val Feb 23 '22 at 08:45
  • @Val here is my question: https://stackoverflow.com/questions/71560909/converting-request-with-or-and-is-is-not-to-nested-bool-query-in-elas – Catalina Mar 21 '22 at 16:28