'ElasticSearch: Need a bool string with AND clauses connected by OR

I have been trying to figure out how to make the following boolean structure in elasticsearch, to no avail:

(name = "Ben" AND car = "Honda") OR (name = "James" AND (car = "Ford" OR car = "Toyota"))



Solution 1:[1]

You can use query_string type of the query with same expression as it support OR and AND operator.

POST carindex/_search
{
  "query": {
    "query_string": {
      "query": "(name:Ben AND car:Honda) OR (name:James AND (car:Ford OR car:Toyota))"
    }
  }
}

Below is boolean query for your condition:

POST carindex/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "name": {
                    "value": "Ben"
                  }
                }
              },
              {
                "term": {
                  "car": {
                    "value": "Honda"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "name": {
                    "value": "James"
                  }
                }
              },
              {
                "terms": {
                  "car": [
                    "Ford",
                    "Toyota"
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

PS: I have consider name and car field as keyword type of field in above query. If you have defined field as multi type of field then you may need to use like name.keyword and car.keyword.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sagar Patel