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;
}
}
One way to achieve this would be the following:
id
property, I changed it to documentId
here. This is necessary, because in Spring Data
Elasticsearch an id-property can be either annotated with @Id
or it can be namend id
. As there can only be one
id-property we need to get this out of the way. It can have the name id in Elasticsearch, set by the @Field
annotation, but the Java property must be changed.@Id
and @AccessType(AccessType.Type.PROPERTY)
which returns the value you
want to use in Elasticsearch.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.