Best way to check if a field exist in an Elasticsearch document

Ekaitz Hernandez Troyas picture Ekaitz Hernandez Troyas · Oct 5, 2015 · Viewed 66.1k times · Source

May be is a very stupid question, What is the best way to check if a field of a document in elasticsearch exists? I can't find anything in the documentation.

For example if this document doesn't have the field/key "price" I don't want to return in the result.

{ "updated": "2015/09/17 11:27:27", "name": "Eye Shadow", "format": "1.5 g / 0.05 oz", }

What I can do?

Thanks

Answer

Val picture Val · Oct 5, 2015

You can use the exists filter combined with a bool/must filter like this:

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "exists": {
                "field": "price"
              }
            },
            ...     <-- your other constraints, if any
          ]
        }
      }
    }
  }
}

DEPRECATED (since ES5) You can also use the missing filter combined with a bool/must_not filter:

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must_not": [
            {
              "missing": {
                "field": "price"
              }
            }
          ]
        }
      }
    }
  }
}