Java client - creating complex bool queries


#1

Let's say we want to match something like this ,
(name="Adam" OR name="Bob) OR (age=21 && email="email@gmail.com")

How to "merge" the expressions in parenthesis with and OR operation

BoolQueryBuilder queryBuilder1 = QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery("name","Adam"))
.should(QueryBuilders.matchQuery("name","Bob"));

BoolQueryBuilder queryBuilder2 = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("age","21"))
.must(QueryBuilders.matchQuery("email","email@gmail.com"));


(David Pilato) #2

You can wrap the two query builders in another bool query with should clauses.


#3

Thank you for the answer. Can you please explain one more thing?

How can I match something like ,

(name="Adam" OR name!="Bob")

BoolQueryBuilder queryBuilder1 = QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery("name","Adam"))
.shouldNot ??? (QueryBuilders.matchQuery("name","Bob")); // ????


(David Pilato) #4

Looks like you could add a boolQuery with a single mustNot clause?

(As NotQuery has been deprecated)


#5

Very well. Thanks again.


(system) #6