Mastering Spring Data Elasticsearch: Clients, Operations, and Query Techniques
This article explains ElasticSearch’s role in modern applications, compares its clients, shows how to configure RestHighLevelClient in Spring Boot, and details the four Spring Data Elasticsearch Operations interfaces with code examples for building queries using CriteriaQuery, StringQuery, and NativeSearchQuery.
ElasticSearch is a widely used search engine that can be integrated into projects; Spring provides official support via Spring Data Elasticsearch, simplifying access.
The main topics covered are:
ElasticSearch use cases and technology background.
Operations and Repository features of spring-data-elasticsearch.
How to add spring-data-elasticsearch to a Spring Boot project.
ElasticSearch Use Cases and Related Technologies
Search functionality is needed not only in Internet applications but also in enterprise projects. Before dedicated search engines, fuzzy queries on relational databases were used, which suffer from low efficiency, slow response, and lack of relevance scoring. Introducing a search engine like ElasticSearch solves these problems.
Besides ElasticSearch, Solr is another popular engine; both are built on Apache Lucene, an open‑source Java library that provides powerful indexing and search capabilities. Lucene Core is a Java library and cannot be used standalone, so enterprises typically choose ElasticSearch or Solr. ElasticSearch stands out for its distributed, real‑time indexing and search capabilities, making it increasingly popular.
Spring Data Elasticsearch Supported Clients
ElasticSearch Clients
ElasticSearch officially provides three clients:
org.elasticsearch.client.transport.TransportClient (deprecated since 7.x and removed in 8.0).
org.elasticsearch.client.RestClient.
org.elasticsearch.client.RestHighLevelClient (the recommended default, also deprecated in the newest versions).
Spring Data Elasticsearch also supports a reactive client, ReactiveElasticsearchClient, which is built on Spring’s WebClient stack.
Creating RestHighLevelClient
Spring Data Elasticsearch offers the AbstractElasticsearchConfiguration interface to simplify RestHighLevelClient creation. Implement this interface and override the elasticsearchClient() method:
@Configuration
public class ESConfiguration extends AbstractElasticsearchConfiguration {
@Override
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("192.168.110.128:9200")
.build();
return RestClients.create(clientConfiguration).rest();
}
}The ClientConfiguration object lets you set properties such as proxy, connection timeout, and socket timeout; the example configures only the host and port.
Using Operations APIs to Work with ElasticSearch
Spring Data Elasticsearch defines four interfaces whose names end with Operations:
IndexOperations
DocumentOperations
SearchOperations
ElasticsearchOperations
Four Operations Interfaces
IndexOperations and DocumentOperations handle index‑level and document‑level actions respectively (e.g., creating/deleting an index, adding or updating a document). Spring provides default implementations such as DefaultIndexOperations (using RestHighLevelClient) and DefaultTransportIndexOperations (using TransportClient), with the former being the recommended choice.
SearchOperation, DocumentOperations, and ElasticsearchOperations share inheritance relationships illustrated below.
ElasticsearchOperations extends both SearchOperation and DocumentOperations, and Spring provides two implementations: ElasticsearchRestTemplate (based on RestHighLevelClient) and ElasticsearchTemplate (based on the older TransportClient).
Search Result Types
SearchHit
Each individual search result is wrapped in a SearchHit object, which contains the entity data plus additional information such as score, highlights, and sort values.
SearchHits
The SearchHits class aggregates multiple SearchHit objects and provides methods to retrieve the list of hits and overall search metadata.
Query Wrappers
Methods in SearchOperations accept a Query parameter. Spring Data Elasticsearch provides three concrete implementations:
CriteriaQuery – builds queries programmatically using a fluent API that mimics SQL keywords.
StringQuery – accepts a JSON string that follows ElasticSearch’s Query DSL.
NativeSearchQuery – combines the power of the native ElasticSearch API for complex queries such as aggregations.
Example of a CriteriaQuery that finds books published in 2021:
Criteria criteria = Criteria.where("publishYear").is(2021);
Query query = new CriteriaQuery(criteria);Example of a CriteriaQuery with a range and additional condition:
Criteria criteria = Criteria.where("publishYear").between(2015, 2019)
.and("category").is("科学技术");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);Example of a CriteriaQuery using sub‑criteria for OR logic:
Criteria criteria = Criteria.where("publishYear").between(2015, 2019)
.subCriteria(Criteria.where("category").is("科学技术").or("category").is("历史人文"));
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);StringQuery example that searches for books in the "历史人文" category published between 2015 and 2019:
Query query = new StringQuery("{
" +
" \"bool\": {
" +
" \"must\": [
" +
" {
" +
" \"match\": {
" +
" \"category\": \"历史人文\"
" +
" }
" +
" },
" +
" {
" +
" \"range\": {
" +
" \"publishYear\": {
" +
" \"gte\": 2015,
" +
" \"lte\": 2019
" +
" }
" +
" }
" +
" }
" +
" ]
" +
" }
" +
" }");
SearchHits<Book> searchHits = operations.search(query, Book.class);NativeSearchQuery is used for more advanced scenarios such as aggregations, but requires familiarity with both the ElasticSearch API and the Spring Data abstraction.
In practice, simple queries are often built with CriteriaQuery, while complex queries are first prototyped in Kibana using DSL and then transferred to code via StringQuery.
Content excerpted from “Spring Boot 从零开始学” by Guo Haoran.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
