1

I was trying to search the following case using BoolQueryBuilder in elasticsearch

 select * from students where (name = "XXX" and rollno = 1) or (name = "YYY" and rollno = 2)

I have to build query builder for it.

Can anyone suggest me the BoolQueryBuilder to build the query.

ElasticSearch 6.1.2

Any help really appreciated.

2 Answers 2

1

This is java api to build the BooleanQueryBuilder condition

        BoolQueryBuilder booleanQuery = QueryBuilders.boolQuery();
        booleanQuery.must(QueryBuilders.termQuery("name", "XXX"));
        booleanQuery.must(QueryBuilders.termQuery("rollno", 1));

        BoolQueryBuilder booleanQuery2 = QueryBuilders.boolQuery();
        booleanQuery2.must(QueryBuilders.termQuery("name", "YYY"));
        booleanQuery2.must(QueryBuilders.termQuery("rollno", 2));

        BoolQueryBuilder boolQueryBuilder3 = QueryBuilders.boolQuery();
        boolQueryBuilder3.should(booleanQuery2);
        boolQueryBuilder3.should(booleanQuery);
Sign up to request clarification or add additional context in comments.

Comments

0

Here it is:

GET students/_search
{
  "query": {
  "bool": {
     "should": [
        {
           "bool": {
              "must": [
                 {
                    "term": {
                       "name": {
                          "value": "XXX"
                       }
                    }
                 },
                 {
                    "term": {
                       "rollno": {
                          "value": "1"
                       }
                    }
                 }
              ]
           }
        },
        {
           "bool": {
              "must": [
                 {
                    "term": {
                       "name": {
                          "value": "YYY"
                       }
                    }
                 },
                 {
                    "term": {
                       "rollno": {
                          "value": "2"
                       }
                    }
                 }
              ]
           }
        }
     ]
  }}}

Basically, bool compound query can apply into deeper level. The rest is about how you use in case of OR or AND operation. In this case, should map to OR, and must map to AND.

Cheers,

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.