I want to update my Elasticsearch indexed document's field. In my case its the tags field. This is the code I currently have:
// Index tags in the page document
$es_client->update([
'index' => 'myappname',
'type' => 'page',
'id' => $page_id,
'body' => [
'doc' => [
'tags' => $tagsArray
]
]
]);
So, this would update my document by adding the tags array to it, but it won't remove the old tags. How can I make sure that the old tags get removed when I add the new tags?
I did look in the documentation, but as we all know, the Elasticsearch docs can be very confusing and all-over-the-place. Hence I am asking here after days of searching.
Any help or advice would be greatly appreciated.
In Elasticsearch, to replace a document you simply have to index a document with the same ID and it will be replaced automatically. If you would like to update a document you can either do a scripted update, a partial update or both. Partial document update: client.
DescriptioneditEnables you to script document updates. The script can update, delete, or skip modifying the document. The update API also supports passing a partial document, which is merged into the existing document. To fully replace an existing document, use the index API.
The update API allows to update a document based on a script provided. The operation gets the document (collocated with the shard) from the index, runs the script (with optional script language and parameters), and index back the result (also allows to delete, or ignore the operation).
Standard update behavior is to merge array/object fields as explained in the update API documentation .
...objects are merged together, existing scalar fields are overwritten and new fields are added.
So instead you would use a script to modify the document source directly. You can make it generic and thus cacheable, and pass in params
for better performance. Php API documentation
// Index tags in the page document
$es_client->update([
'index' => 'myappname',
'type' => 'page',
'id' => $page_id,
'body' => [
'script' => 'ctx._source.tags=tags',
'params' => ['tags' => $tagsArray]
]
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With