问题
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:
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.
来源:https://stackoverflow.com/questions/28897404/spring-data-elasticsearchs-elasticsearchtemplate-vs-elasticsearchrepository