'Elasticsearch check if key exist in document

I have key "field1" in the document of Elasticsearch. With mapping the field is an object. sometimes field does not exist, sometimes the field exists but is empty ([]), sometimes the field has the correct value -

"field1": [
   {"key" : "value"},
   {"key" : "value1"}
]

Now I want to write a filter with script query but get this kind of error

"caused_by": {
     "type": "illegal_argument_exception",
     "reason": "No field found for [field1] in mapping with types []"
   }

Even when I write a simpler query

if (doc.containsKey('field1')) {return true;} else {return false;}

but I have many documents which have the field. I think containsKey doesn't check the first level in a document but checks the full path.

Can somebody help me to check field1 exists in document or not



Solution 1:[1]

You can use the exists query.

{
    "query": {
        "exists": {
            "field": "field1"
        }
    }
}

As mentioned in the exists query document, if field as null or [](your case), it will not be indexed and exists query will not return that document.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amit