Updating Documentsedit
Updating a document allows you to either completely replace the contents of the existing document, or perform a partial update to just some fields (either changing an existing field, or adding new fields).
Partial document updateedit
If you want to partially update a document (e.g. change an existing field, or add a new one) you can do so by specifying
the doc
in the body
parameter. This will merge the fields in doc
with the existing document
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'body' => [ 'doc' => [ 'new_field' => 'abc' ] ] ]; // Update doc at /my_index/my_type/my_id $response = $client->update($params);
Scripted document updateedit
Sometimes you need to perform a scripted update, such as incrementing a counter or appending a new value to an array. To perform a scripted update, you need to provide a script and (usually) a set of parameters:
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'body' => [ 'script' => 'ctx._source.counter += count', 'params' => [ 'count' => 4 ] ] ]; $response = $client->update($params);
Upsertsedit
Upserts are "Update or Insert" operations. This means an upsert will attempt to run your update script, but if the document does not exist (or the field you are trying to update doesn’t exist), default values will be inserted instead.
$params = [ 'index' => 'my_index', 'type' => 'my_type', 'id' => 'my_id', 'body' => [ 'script' => 'ctx._source.counter += count', 'params' => [ 'count' => 4 ], 'upsert' => [ 'counter' => 1 ] ] ]; $response = $client->update($params);