2

I have address doc type which has city as field. The city field uses analyser

"keyword_analyzer": {
  "tokenizer": "keyword", # So that we don't split multi word city name
  "filter": ["lowercase"] # The search needs to case insensitive
}

How can I get any address which matches the give city 'X' or city is null. In sql it would be written as

SELECT * FROM address
WHERE city = 'X' or city IS NULL

I guess I have to use match query to get city ='X' and 'missing' filter to get city IS NULL. How can I combine this?

1 Answer 1

4

Elasticsearch allows to combine queries with the bool query. Bool query has three fields:

  • must (AND)
  • should (OR)
  • must_not (AND NOT)

The following elasticsearch query is a boolean query containing a should field, with two sub-queries:

  • the first selects items with city field containing at least one token == "myCity"
  • the second selects items without city field

Results of this query will be equivalent to city = 'mycity' OR city IS NULL:

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "city": "mycity"
          }
        },
        {
          "filtered": {
            "query": {
              "match_all": {}
            },
            "filter": {
              "missing": {
                "field": "city"
              }
            }
          }
        }
      ]
    }
  }
}

Some useful resources:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.