javaspringelasticsearchspring-data-elasticsearchcomposite-key

Can we use Composite Primary Key Mapping in spring data elastic search


I have an entity 'Product' and I want the primary key in ES to be used as a combination of 'id' and 'name' attributes. How can we do that using spring data elastic search.

public class Product {
    @Id
    private String id;

    @Id
    private String name;

    @Field(type = FieldType.Keyword)
    private Category category;

    @Field(type = FieldType.Long)
    private double price;

    @Field(type = FieldType.Object)
    private List<ValidAge> age;

    public enum Category {
        CLOTHES,
        ELECTRONICS,
        GAMES;
    }
}

Solution

  • One way to achieve this would be the following:

    So that comes up with an entity like this:

    @Document(indexName = "composite-entity")
    public class CompositeEntity {
    
        @Field(name="id", type = FieldType.Keyword)
        private String documentId;
    
        @Field(type = FieldType.Keyword)
        private String name;
    
        @Field(type = FieldType.Text)
        private String text;
    
        @Id
        @AccessType(AccessType.Type.PROPERTY)
        public String getElasticsearchId() {
            return documentId + '-' + name;
        }
    
        public void setElasticsearchId(String ignored) {
        }
    
        // other getter and setter
    }
    
    

    The repository definition would be straight forward:

    public interface CompositeRepository extends ElasticsearchRepository<CompositeEntity,
        String> {
    }
    

    Remember that for every method that needs an Elasticsearch Id, you'll need to create like it's done in the entity class.