Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Elasticsearch 'must not' with OR operator

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading