Raviteja Gannoju
Raviteja Gannoju

Reputation: 117

building compound query in elasticsearch

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.

Upvotes: 1

Views: 359

Answers (2)

Raviteja Gannoju
Raviteja Gannoju

Reputation: 117

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);

Upvotes: 1

ThangTD
ThangTD

Reputation: 1684

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,

Upvotes: 0

Related Questions