Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch update id of each document to a value of another field in the document

In elasticsearch how can I replace the id of every document with the value of another field in the document?

like image 989
windup Avatar asked Nov 05 '25 02:11

windup


1 Answers

I don't think you can change the ids of existing documents in the index, but you can reindex them using the path parameter in your mapping. Here is a trivial example.

I set up a simple index, using the path parameter in the _id definition in the mapping, and added a few docs:

PUT /test_index
{
    "mappings": {
        "doc":{
            "_id": {
                "path": "number"
            },
            "properties": {
                "text_field": {
                    "type": "string"
                },
                "number": {
                    "type": "integer"
                }
            }
        }
    }
}

POST /test_index/doc/_bulk
{"index":{}}
{"text_field": "Apple TV","number":3}
{"index":{}}
{"text_field": "Apple iPhone","number":2}
{"index":{}}
{"text_field": "Apple MacBook","number":1}

Then if I search, I can see that the ids were set as I asked:

POST /test_index/_search
...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 3,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "1",
            "_score": 1,
            "_source": {
               "text_field": "Apple MacBook",
               "number": 1
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "2",
            "_score": 1,
            "_source": {
               "text_field": "Apple iPhone",
               "number": 2
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "3",
            "_score": 1,
            "_source": {
               "text_field": "Apple TV",
               "number": 3
            }
         }
      ]
   }
}

Here's the code I used:

http://sense.qbox.io/gist/933bd839b2d524889e483f50c59c37ffaab2270a

like image 93
Sloan Ahrens Avatar answered Nov 08 '25 07:11

Sloan Ahrens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!