Search code examples
elasticsearchelastic-stackaws-elasticsearch

How to apply a OR filter on same field with different values in elasticsearch query


I am looking to add a filter on the same field with different values. Basically i want to get the docs with filter of type mode1 or mode2. Something is wrong in the below query.

 {
   "index": "abcdef*",
   "from": 0,
   "size": 50,
   "body": {
   "query": {
     "bool": {
         "must": [{ "term": { "id": "123455" } }],
         "filter": [{ "term": { "mode": "mode1" } }, { "term": { "mode": "mode2" } }]
     }
   } 
  }
 }

Solution

  • It's better to move bool/should at the top level and use bool/filter instead of bool/must for the term query (as you don't need relevance, just a yes/no answer for the constraint on the id field):

    {
      "query": {
        "bool": {
          "minimum_should_match": 1,
          "should": [
            {
              "term": {
                "mode": "mode1"
              }
            },
            {
              "term": {
                "mode": "mode2"
              }
            }
          ],
          "filter": [
            {
              "term": {
                "id": "123455"
              }
            }
          ]
        }
      }
    }
    

    Or even better, simply leverage the terms query which makes the query as simple as it gets:

    {
      "query": {
        "bool": {
          "filter": [
            {
              "term": {
                "id": "123455"
              }
            },
            {
              "terms": {
                "mode": ["mode1", "mode2"]
              }
            }
          ]
        }
      }
    }