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?
Spring Data Spring Data helps avoid boilerplate code. For example, if we define a repository interface that extends the ElasticsearchRepository interface that Spring Data Elasticsearch provides, CRUD operations for the corresponding document class will become available by default.
The ElasticsearchTemplate class is deprecated as it uses the TransportClient to access Elasticsearch, which itself is deprecated since Elasticsearch version 7.+ Users should switch to ElasticsearchRestTemplate or ReactiveElasticsearchTemplate.
Elasticsearch configuration Spring Boot 2.4.0 does not require any special configuration for ElasticSearch, as everything is taken care by ElasticsearchRestClientAutoConfiguration configuration class. We just need to provide the below configuration in application yal to trigger the automatic bean creation:
Elasticsearch is an open source, distributed full-text search engine that provides REST api for indexing, searching etc. The major components of elasticsearch are: Documents are JSON objects that are stored within an Elasticsearch index and are considered as the base unit of storage.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With