javaelasticsearchlogical-operatorsbooleanquery

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.


Solution

  • 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,