3

I want to create a query with Elasticsearch Java API but I don't know how to create an OR clause? What I want to query is;

SELECT * 
FROM USERS 
WHERE (user.name = "admin") AND (user.message LIKE "test*") AND (user.age = "30" OR user.status = "major")

I have created a query like below but I don't know how to create an OR clause like sql query;

BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

boolQueryBuilder.must(QueryBuilders.matchQuery("name", "admin"));
boolQueryBuilder.must(QueryBuilders.matchQuery("message", "test*"));

boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
boolQueryBuilder.must(QueryBuilders.matchQuery("status","major"));

2 Answers 2

9

You simply need to capture the OR condition inside another bool/should query

BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

boolQueryBuilder.must(QueryBuilders.matchQuery("name", "admin"));
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("message", "test*"));

BoolQueryBuilder orQuery = QueryBuilders.boolQuery();
orQuery.should(QueryBuilders.matchQuery("age", "30"));
orQuery.should(QueryBuilders.matchQuery("status","major"));
orQuery.minimumNumberShouldMatch(1);
boolQueryBuilder.must(orQuery);

PS: not sure why you have a mustNot for your second constraint.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry my mistake its not "mustNot". By the way is my "like" query is correct? (I mean QueryBuilders.matchQuery("message", "test*"))
You cannot have wildcards in match queries, but you can use a queryStringQuery or a wildcardQuery instead
0

The "should" keyword in bool queries works like "OR", but in Elasticsearch those queries are not very sharp as everything is scored. Have a look at:

https://www.elastic.co/guide/en/elasticsearch/guide/current/bool-query.html#bool-query

Also there are very good examples in the book Elasticsearch in Action.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.