11

I am in reference to Spring Data Elasticsearch's

  • org.springframework.data.elasticsearch.repository.ElasticsearchRepository
  • org.springframework.data.elasticsearch.core.ElasticsearchTemplate

It seems they are two different APIs that achieve the same goal but I am not sure what the differences are between those two types and more importantly when to use which.

Can someone please provide advice and guidance?

1 Answer 1

11

ElasticsearchRepository is intended to be used as a repository for your domain classes, as it's typed. It extends Spring interfaces for repositories so it can used as one of them. You'll feel very comfortable with it if you are used to Spring repositories.

All you need to start indexing your objects to Elasticsearch is to add the @Document annotation to them and create a Repository interface extending ElasticsearchRepository.

The indexable class:

@Document(
    indexName = "customers", 
    type = "customer", 
    shards = 1, 
    replicas = 0, 
    refreshInterval = "-1"
)
public class Customer {
    @Id
    private Long id;
    private String name;

    public Customer() { 
    }

    public Customer(String name) {
        this.name = name;
    }

    //Getters and setters omited
}

The repostitory:

public interface CustomerRepository 
    extends ElasticsearchRepository<Customer, Long>{
}

With this you can, out of the box, make CRUD operations, index, search and other common operations.

ElasticsearchTemplate, by other hand, is an elasticsearch client for working with your indexes, and it's not typed or related to your domain classes. It's more powerful since you can do many tasks not available to the repository implementation, like deleting an index or making aggregated searchs.

Sign up to request clarification or add additional context in comments.

2 Comments

Is this still up to date? When running code thats the same as yours, Spring now tells me to add a bean called elasticsearchTemplate.
I have the same issue. It asks me to add elasticsearchTemplate to my class? Do you know why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.