Skip to content
Advertisement

How to update the Elasticsearch document with Python?

I am using the code below to add data to Elasticsearch:

JavaScript

But how do I update the document?

JavaScript

Here Dr. Messi, Dr. Christiano has to update the index and Dr. Bernard M. Aaron should not update as it is already present in the index.

Advertisement

Answer

In Elasticsearch, when data is indexed without providing a custom ID, then a new ID will be created by Elasticsearch for every document you index.

Hence, since you are not providing an ID, Elasticsearch generates it automatically.

But you also want to check if Name already exists. There are two approaches:

  1. Index the data without passing an _id for every document. After this you will have to search using the Name field to see if the document exists.
  2. Index the data with your own _id for each document. Then search with _id.

I’m going to demonstrate the second approach of creating our own IDs. Since you are searching on the Name field, I’ll hash it using MD5 to generate the _id. (Any hash function could work.)

First Indexing Data:

JavaScript

Output:

JavaScript

Next Step: Indexing new data

JavaScript

Output:

JavaScript

As you can see Dr. Bernard M. Aaron record is not indexed as it’s already present

Advertisement