Search code examples
python-3.xelasticsearchpython-3.6elastic-stack

How to give my own _id while inserting data in Elasticsearch?


I have a sample database as below:

SNO Name Address
99123 Mike Texas
88124 Tom California

I want to keep my SNO in elastic search _id to make it easier to update documents according to my SNO.

Python code to create an index:

    abc = {
    "settings": {
        "number_of_shards": 2,
        "number_of_replicas": 2
    }
}

es.indices.create(index='test',body = abc)

I fetched data from postman as below:

{
"_index": "test",
"_id": "13",
"_data": {
    "FirstName": "Sample4",
    "LastName": "ABCDEFG",
    "Designation": "ABCDEF",
    "Salary": "99",
    "DateOfJoining": "2020-05-05",
    "Address": "ABCDE",
    "Gender": "ABCDE",
    "Age": "21",
    "MaritalStatus": "ABCDE",
    "Interests": "ABCDEF",
    "timestamp": "2020-05-05T14:42:46.394115",
    "country": "Nepal"
}

}

And Insert code in python is below:

req_JSON = request.json 
input_index = req_JSON['_index']
input_id = req_JSON['_id']
input_data = req_JSON['_data']    
doc = input_data 
res = es.index(index=input_index, body=doc) 

I thought _id will remain the same as what I had given but it generated the auto _id.


Solution

  • You can simply do it like this:

    res = es.index(index=input_index, body=doc, id=input_id) 
                                                    ^
                                                    |
                                                 add this