Document Upserts
An upsert operation is a combination of an update and insert. If the document exists, it is updated; if it does not exist, a new document is created. This can be done using the _update API with an upsert clause.
Example: Upserting a Document
Assume we want to upsert a document in myindex.
Step 1: Preparing the Upsert Operation
We’ll attempt to update a document with ID 2. If it doesn’t exist, it will be created.
curl -X POST "http://localhost:9200/myindex/_update/2" -H 'Content-Type: application/json' -d'
{
"doc": {
"name": "Jane Doe",
"age": 25,
"city": "San Francisco"
},
"doc_as_upsert": true
}'
Output:
If the document doesn’t exist, it will be created:
{
"_index": "myindex",
"_id": "2",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
If the document exists, it will be updated:
{
"_index": "myindex",
"_id": "2",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
Handling Document Updates, Deletes, and Upserts in ElasticsearchHandling Document Updates, Deletes, and Upserts in Elasticsearch: Best Practices
Elasticsearch is a robust search engine widely used for its scalability and powerful search capabilities. Beyond simple indexing and querying, it offers sophisticated operations for handling document updates, deletes, and upserts. This article will explore these operations in detail, providing easy-to-understand examples to help you get started.