1

I am trying to write some Java code to query an ES5 instance. In ES1, you could OR and AND filters, orFilter and andFilter. What is the equivalent in ES5? I have tried -

QueryBuilder fb1 = QueryBuilders.termQuery("term1", "value1");
QueryBuilder fb2 = QueryBuilders.termQuery("term1", "value2");
QueryBuilder fb3 = QueryBuilders.termQuery("term2", "value3");

QueryBuilder fb = QueryBuilders.boolQuery()
                        .must(fb1)
                        .should(fb2)

This gives results that match fb1, so this is not an OR

QueryBuilder fb = QueryBuilders.boolQuery()
                        .must(fb1)
                        .must(fb2)

This gives no results, so the AND worked.

I want to figure out ways of constructing AND, OR queries

3 Answers 3

2

In order to make an AND query, put all the conditions into "must".

QueryBuilder fb = QueryBuilders.boolQuery().must(fb1).must(fb2);

In order to make an OR query, put all the conditions into "should".

QueryBuilder fb = QueryBuilders.boolQuery().should(fb1).should(fb2);
Sign up to request clarification or add additional context in comments.

Comments

0

From ElasticSearch documentation (https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-compound-queries.html):

QueryBuilder qb = boolQuery()
    .must(termQuery("content", "test1"))    
    .must(termQuery("content", "test4"))    
    .mustNot(termQuery("content", "test2")) 
    .should(termQuery("content", "test3"))  
    .filter(termQuery("content", "test5")); 

must seems like it might be the equivalent of the AND and should like it's the equivalent of the OR.

2 Comments

What doesn't work? Can you post what you are trying?
QueryBuilder fb = QueryBuilders.boolQuery() .should(fb1) .should(fb2) to get the or
0

You can use BoolQueryBuiler for these filters :

BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("customerId", customerId))

boolQueryBuilder.mustNot(QueryBuilders.termsQuery("reason", "failed"));

                    boolQueryBuilder.should(QueryBuilders.termsQuery("action", "deny")).minimumNumberShouldMatch(1);

QueryBuilder queryBuilder=boolQueryBuilder;

new SearchContext().prepareSearch(sc.getIndexNames()).setTypes(sc.getTypeName()).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(queryBuilder);

2 Comments

I'm not sure I understand the above. How are you achieving an OR query?
Using minimumNumberShouldMatch(1) --> you can add multiple should filters and if you setminimumNumberShouldMatch as one ,it will at least try to match one of those filters .

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.