Automatically generate numerical id when using ElasticSearch with Spring Data

Viewed 1881

I am currently converting a project I did from Spring Data with Hibernate to Spring Data with ElasticSearch.

Before, I was able to auto generate the id of my entity using the annotation @GeneratedValue(strategy = GenerationType.IDENTITY). This way, when the entity is saved, an id number is generated for it.

However, I can't seem to find an annotation that ElasticSearch uses to achieve the same result.

The entity using Hibernate annotation:

@Entity
@Table(name = "person")
public class Person {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private int age;

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }

Is there an ElasticSearch equivalent to the @GeneratedValue annotation? If not, what is the optimal way to populate the id field when using ElasticSearch?

3 Answers

I just ran into the same issue and looks like there is no annotation as such but we can write a component by defining a custom BeforeConvertCallback that sets an id if necessary.

@Component
public class BookBeforeConvertCallback implements BeforeConvertCallback<Book> {

    @Override
    public Book onBeforeConvert(Book book, IndexCoordinates indexCoordinates) {

        if (book.getId() == null) {
            book.setId(UUIDs.randomBase64UUID());
        }

        return book;
    }
}

Ref: https://github.com/spring-projects/spring-data-elasticsearch/issues/616#issuecomment-752866566

Related