Elasticsearch 'must not' with OR operator

Advertisements

I am looking to do below with a Elasticsearch query,

-> filter by condition X

-> get records that do not satisfy either condition A or condition B

To do this I had below initially, then realized that ‘must_not’ does AND between conditions A and B.

{
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "district_id": {
                            "value": 123456
                        }
                    }
                }
            ],
            "must_not": [
                {
                    "match": {
                        "district_name": {
                            "query": "Mydist"
                        }
                    }
                },
                {
                    "term": {
                        "state_id": {
                            "value": 123
                        }
                    }
                }
            ]
        }
    }
}

Some of the solutions suggested are quite confusing, I was wondering if there is an easy-to-understand solution. I am on version 7.13.

>Solution :

You’re almost there. You just need to bury two must_not clauses into a top-level bool/should. The query you’re looking for is this one:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "district_id": {
              "value": 123456
            }
          }
        }
      ],
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "must_not": [
              {
                "match": {
                  "district_name": {
                    "query": "Mydist"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "term": {
                  "state_id": {
                    "value": 123
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Leave a ReplyCancel reply