1

I have a spring data elastic search document as follows :

@Document(indexName = "outlet")
public class OutletIndex implements IESMapper{

    @Id
    private String name;
    private Long outletId;
    private OutletType type;
    private String address;
    private String geoLocation;
    private String city;

    // getter and setter methods

}

Can I make the combination of city and name field unique? In spring data jpa we can use @UniqueConstraint option(How to introduce multi-column constraint with JPA annotations?). Is there any way to implement it in Spring data ES?

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188

1 Answers1

1

There is no concept of unicity in Elasticsearch except the _uid field, which is a concatenation of the mapping type and the document _id, e.g. outlet#someName

Instead of using the name as the document @Id, you could create another field called cityName which would be the concatenation of the city and the name fields. This alone guarantees that no two documents will have the same city and name field values, i.e. some kind of lightweight unicity constraint.

In addition, if you want the indexing operation to fail if a second document with the same name/city is indexed, then, when creating new documents, instead of hitting the usual index API with PUT index/type/someNameSomeCity you'd hit the _create endpoint like this

`PUT index/type/123/someNameSomeCity/_create`
or
`PUT index/type/123/someNameSomeCity?op_type=create`

The effect will be that if a document with the same someNameSomeCity ID already exists, then the indexing operation will fail, which also implicitly guarantees some sort of unicity.

Val
  • 207,596
  • 13
  • 358
  • 360