Elasticsearch Update API if a field does not exist

elasticsearch

Solution

You can use the update script to check if field exists:

curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{
    "script" : "if( ctx._source.containsKey(\"counter\") ){ ctx._source.counter += count; } else { ctx._source.counter = 1; }",
    "params" : {
        "count" : 4
    },
    "upsert" : {
        "counter" : 1
    }
}'

Problem

The example for upsert is: ``` curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{ "script" : "ctx._source.counter += count", "params" : { "count" : 4 }, "upsert" : { "counter" : 1 } }' ``` which works if the document does not exist previously. Say i want to update a field that does not necessarily exist, but the document exists. For example, the document might not have a counter field yet. How do I go about doing that?

Original source