Spring Data Elasticsearch's ElasticsearchTemplate vs ElasticsearchRepository

二次信任 提交于 2021-02-18 21:32:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!