Search code examples
elasticsearch

ElasticSearch combined OR and AND clauses in filter


I have a ElasticSearch 7.7 query with several filters (criteria that I don't want to be counted for the score), that look like that:

{
  "from": 0,
  "size": 100,
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": [
        {
          "term": {
            "type": 4
          }
        },
        {
          "term": {
            "gender": "female"
          }
        }
      ]
    }
  }
}

I would like to add a OR clause to two gender filters, in order to filter for all documents with a type=4 AND (gender=female OR gender=unisex). Is this possible?


Solution

  • You can use should clause

    {
      "from": 0,
      "size": 100,
      "query": {
        "bool": {
          "must": {
            "match_all": {}
          },
          "filter": [
            {
              "term": {
                "type": 4
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "term": {
                      "gender": "female"
                    }
                  },
                  {
                    "term": {
                      "gender": "unisex"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }