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.

Raviteja Gannoju
  • 117
  • 3
  • 16

2 Answers2

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);
Raviteja Gannoju
  • 117
  • 3
  • 16
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,

ThangTD
  • 1,586
  • 17
  • 16