Search code examples
javaelasticsearchspring-data-elasticsearch

Can we fetch the metadata `_version` of existing document using Spring-data-elasticsearch?


I am implementing a feature where I need to compare the metadata version of an existing document before indexing it and I have a version attribute in my object which can't be the same as the metadata version. Can I fetch the metadata version explicitly in code, so that I can compare ? I am using spring-data-elasticsearch. I will appreciate any help.


Solution

  • You just have to add a property annotated with @Version to your entity, for example:

    @Document(indexName = "person")
    public class Person {
    
        @Id
        @Nullable
        private Long id;
    
        @Nullable @Version
        Long version;
    
        // other properties, getter and setter
    }
    

    When reading entities with Spring Data Elasticsearch, this property - which must be a Long - will be set to the value returned from Elasticsearch.