Search code examples
elasticsearchelasticsearch-dsl

What Elasticsearch DSL is needed to create a compound AND-OR query?


I must apologise if this is rather trivial, but I am quite new to the Elasticsearch (8.5) world and struggling a bit to find a suitable solution from the documentation.

Ultimately, the goal is to create a DSL that represents:

(attr1 IS NOT NULL AND attr2 IS NULL) 
  OR (attr3 IS NOT NULL AND attr4 IS NULL) 
  OR attr5 = true

I started down the scoring path but cannot get consistent results.

Any advice is greatly appreciated.


Solution

  • You can use below DSL query:

    Here, I put all the 3 OR condition into should clause and all the inner AND condition into bool clause.

    exists query inside must for checking not null value and exists query inside must_not for checking null value.

    Please note that exists query with must_not will work only if you dont have field in document or field is set as null. it will not work if field is having empty string value.

    {
      "query": {
        "bool": {
          "should": [
            {
              "bool": {
                "must": [
                  {
                    "exists": {
                      "field": "attr1"
                    }
                  }
                ],
                "must_not": [
                  {
                    "exists": {
                      "field": "attr2"
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "must": [
                  {
                    "exists": {
                      "field": "attr3"
                    }
                  }
                ],
                "must_not": [
                  {
                    "exists": {
                      "field": "attr4"
                    }
                  }
                ]
              }
            },
            {
              "term": {
                "attr5": {
                  "value": true
                }
              }
            }
          ]
        }
      }
    }