Elasticsearch update API if field does not exist

Example for upsert:

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 did not exist previously.

Let's say I want to update a field that does not necessarily exist, but the document exists. For example, a document may not have a counter field.

How should I do it?

+5
source share
2 answers

You can use an update script to check if a 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
    }
}'
+9
source

doc, . , , . .

,

(1) field1

curl -XPOST localhost:9200/myidx/mytp/myid?pretty -d '{
    "field1" : 1
}'

"_source" : {
    "field1" : 1
}

(2) field2

curl -XPOST localhost:9200/myidx/mytp/myid/_update?pretty -d '{
    "doc" : {
        "field2" : 2
    }
}'

"_source" : {
    "field1" : 1,
    "field2" : 2
}

(3) ,

curl -XPOST localhost:9200/myidx/mytp/myid/_update?pretty -d '{
    "doc" : {
        "field2" : 200, 
        "field3" : 3
    }
}'

"_source" : {
  "field1" : 1,
  "field2" : 200,
  "field3" : 3
}
0

All Articles