Shilpa Nagavara
Shilpa Nagavara

Reputation: 1165

Elastic Search Query: (A or B) and (C or D)

I have an elastic search index where the columns are Country and Expertise. I need to write a query where I can get records whose Country is (USA or UK) AND Expertise is (Botany or Physics)

How do I write this query?

Upvotes: 3

Views: 3514

Answers (1)

hkulekci
hkulekci

Reputation: 1942

You can use bool and terms query to do this like below:

{
    "query": {
        "bool": {
            "must": [
               {
                   "terms": {
                      "Country": [
                         "USA",
                         "UK"
                      ]
                   }
               },
               {
                   "terms": {
                      "Expertise": [
                         "Botany",
                         "Physics"
                      ]
                   }
               }
            ]
        }
    }
}

On the other hand you can only use bool query to do this:

{
    "query": {
        "bool": {
            "must": [
               {
                   "bool": {
                       "should": [
                          {
                              "term": {
                                 "Country": {
                                    "value": "USA"
                                 }
                              }
                          },
                          {
                              "term": {
                                 "Country": {
                                    "value": "UK"
                                 }
                              }
                          }
                       ]
                   }
               },
               {
                   "bool": {
                       "should": [
                          {
                              "term": {
                                 "Expertise": {
                                    "value": "Botany"
                                 }
                              }
                          },
                          {
                              "term": {
                                 "Expertise": {
                                    "value": "Physics"
                                 }
                              }
                          }
                       ]
                   }
               }
            ]
        }
    }
}

But, please look documentation before asking any other question. Maybe, you may find a shorter query.

Upvotes: 4

Related Questions