Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch Update API if a field does not exist

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?

like image 725
eran Avatar asked Apr 12 '13 09:04

eran


People also ask

How do I update a document in Elasticsearch?

Updates a document using the specified script. If the Elasticsearch security features are enabled, you must have the index or write index privilege for the target index or index alias. Enables you to script document updates.

How to call the Elasticsearch client’s update () method in Python?

How to call the Elasticsearch client’s update () method to update an index’s document. The structure of Python’s Update () method should, at the very minimum, include the index name, it’s document type (depreciated), the document ID and the content “”body”” that is being updated, as shown here:

How do I get Elasticsearch to always reindex a document?

By default, the document is only reindexed if the new _source field differs from the old. Setting detect_noop to false will cause Elasticsearch to always update the document, even if it hasn’t changed.

Why don't we have input fields in Elasticsearch?

input fields weren't required and were skipped (e.g. optional input fields in signup forms) because of human error (e.g. data entry "interns" forgot to fill out a form field) and last but not least, because of purposefully set empty-ish values ( null, [], {}, "") In Elasticsearch, these values would indicate that a given field does exist:


1 Answers

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
    }
}'
like image 168
imotov Avatar answered Sep 20 '22 23:09

imotov