Search code examples
elasticsearchelasticsearch-java-api

Elasticsearch Java Api: set a field as _id


I want to ask if the unique field _id be assigned by certain field within document. I see with Rest, it can achieve by path:

{
  "tweet": {
    "_id": {
      "path": "post_id"
    }
  }
}

But if I want to do it with java API, is there any way to achieve it?

Map<String, Object> MapA= new HashMap<String, Object>();
MapA=MapProcessor(MapA);

client.prepareIndex("index","type").setSource(MapA).execute().actionGet();

How could I modify my code to assign certain field in Map to become _id of this type?


Solution

  • just provide id while indexing, like this

    Map<String, Object> MapA= new HashMap<String, Object>();
    MapA=MapProcessor(MapA);
    
    client.prepareIndex("index","type",MapA.get("post_id")).setSource(MapA).execute().actionGet();
    

    If you don't want to do this, add this as mapping then.

    {
        "tweet" : {
            "_id" : {
                "path" : "post_id"
            }
        }
    }
    

    if you add post_id field to elasticsearch, then it will become "_id" too .