Search code examples
elasticsearchspring-data-elasticsearch

How to set id as an unique value for a document in Elasticsearch


How to set id as an unique value (say jNsY9nYBnpr12MYNt7D0 or i9sY9nYBnpr12MYNtrAm) for a document in Elasticsearch before its being persisted. What utility function should we use to auto generate the string in the above form


Solution

  • When you save an entity with Spring Data Elasticsearch the methods that do the save will return the saved entity. If the @Id field was set to null before saving, the returned entity will have it set to the value that Elasticsearch created.

    But as @Val pointed out: Don't do this, there's no need for this.

    If you nevertheless want to create the id yourself, you might use the org.elasticsearch.common.UUIDs#base64UUID method, that's what Elasticsearch uses.