Create a document with the update API if the document doesn’t exist yet

elasticsearch

I have a very simple question :

I want to update multiple documents to elasticsearch. Sometimes the document already exists but sometimes not. I don't want to use a get request to check the existence of the document (this is decreasing my performance). I want to use directly my update request to index the document directly if it doesn't exist yet.

I know that we can use upsert to create a non existing field when updating a document, but this is not what I want. I want to index the document if it doesn't exist. I don't know if upsert can do this.

Can you provide me some explaination ?

Thanks in advance!

Best Solution

This is doable using the update api. It does require that you define the id of each document, since the update api requires the id of the document to determine its presence.

Given an index created with the following documents:

PUT /cars/car/1 
{ "color": "blue", "brand": "mercedes" }
PUT /cars/car/2
{ "color": "blue", "brand": "toyota" }

We can get the upsert functionality you want using the update api with the following api call.

POST /cars/car/3/_update
{
    "doc": {
        "color" : "brown",
        "brand" : "ford"
    },
    "doc_as_upsert" : true
}

This api call will add the document to the index since it does not exist.

Running the call a second time after changing the color of the car, will update the document, instead of creating a new document.

POST /cars/car/3/_update
{
    "doc": {
        "color" : "black",
        "brand" : "ford"
    },
    "doc_as_upsert" : true
}
Related Question