Kamboh
Kamboh

Reputation: 185

search document with null/empty object field in elasticsearch

I have an elasticsearch index with following mapping, some documents contain objects of status {id:1, status:"failed"} and some are null, cant seem to find a way where i can search for documents having "status.name" as ["failed", "null", "passed"] (docs where either status is failed, passed or not set/null). e.g doing a term query like below gives empty resultset

{
"name":{
"type":"keyword"
}
 "status": {
                "properties": {
                    "id": {
                        "type": "integer"
                    },
                    "status": {
                        "type": "keyword"
                    }
                }
            }
}

query tried:

{
"terms": {
  "status.name": [  "failed", "null" ]
   }

Also tried setting the mapping of status.name as "null_value": "null"

Upvotes: 1

Views: 3107

Answers (1)

Daniel Schneiter
Daniel Schneiter

Reputation: 1996

Use a bool query with only should clauses, making it a requirement that at least one of your queries must match. You can query for documents not having a field or having a null-value in that field by putting an exists-query into the must_not-clause of a bool-query (see Elasticsearch Reference: Exists-query).

GET myindex/_search
{
  "query": {
    "bool": {
      "should": [
        {"term": {"status.name": {"value": "failed"}}},
        {"term": {"status.name": {"value": "passed"}}},
        {"bool": {"must_not": {"exists": {"field": "status.name"}}}}
      ]
    }
  }
}

Upvotes: 3

Related Questions