Search code examples
elasticsearchsearchelasticsearch-dsl

Elastic search combine match and should


I want to create a query where i can use match, and that match should only consider rows where another field value is null or some specific value.

So something like:

where field1 like 'string' and field2 is null or field2 = 123

Is that possible in JS client?


Solution

  • You can use a combination of bool/must/should along with the exists and wildcard query

    {
      "query": {
        "bool": {
          "must": [
            {
              "wildcard": {
                "field1": "string*"
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "term": {
                      "field2": 123
                    }
                  },
                  {
                    "bool": {
                      "must_not": {
                        "exists": {
                          "field": "field2"
                        }
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }