Spring Boot Integration with Elasticsearch: Dependency Setup, High-Level Client, and CRUD Operations
The article provides a step‑by‑step guide for integrating Elasticsearch into a Spring Boot project, including Maven dependency configuration, creating a RestHighLevelClient, performing index and document CRUD operations, bulk processing, and advanced search queries with highlighting.
This article demonstrates how to integrate Elasticsearch into a Spring Boot application, covering Maven dependency configuration, high‑level client creation, and a range of CRUD operations for indices and documents.
1. Import Elasticsearch Dependency
Add the following dependency to pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>Ensure the version matches your Spring Boot version to avoid connection failures.
2. Create High‑Level Client
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("服务器IP", 9200, "http")));
return client;
}
}3. Basic Index CRUD
3.1 Create, Check Existence, Delete Index
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
class ElasticsearchApplicationTests {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
void testCreateIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("ljx666");
CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response);
}
@Test
void testExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("ljx666");
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("ljx666");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
}3.2 Document CRUD
Create Document
@Test
void testAddUser() throws IOException {
// 1. Create object
User user = new User("Go", 21, new String[]{"内卷", "吃饭"});
// 2. Create request
IndexRequest request = new IndexRequest("ljx666");
request.id("6");
request.timeout("1s");
request.source(JSONValue.toJSONString(user), XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse);
System.out.println(indexResponse.status());
}Get Document
@Test
void testGetUser() throws IOException {
GetRequest request = new GetRequest("ljx666", "1");
GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
System.out.println(getResponse);
System.out.println(getResponse.getSourceAsString());
}Update Document
@Test
void testUpdateUser() throws IOException {
UpdateRequest request = new UpdateRequest("ljx666", "6");
User user = new User("GoGo", 21, new String[]{"内卷", "吃饭"});
request.doc(JSONValue.toJSONString(user), XContentType.JSON);
UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
}Delete Document
@Test
void testDeleteUser() throws IOException {
DeleteRequest request = new DeleteRequest("ljx666", "6");
DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}3.3 Bulk CRUD
@Test
void testBulkAddUser() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> list = new ArrayList<>();
list.add(new User("Java", 25, new String[]{"内卷"}));
// ... add more users ...
int id = 1;
for (User u : list) {
bulkRequest.add(new IndexRequest("ljx666")
.id("" + (id++))
.source(JSONValue.toJSONString(u), XContentType.JSON));
}
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());
}4. Search Queries
@Test
void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("ljx666");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 1. Match all
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 2. Multi‑match on name field
sourceBuilder.query(QueryBuilders.multiMatchQuery("java", "name"));
// 3. Pagination
sourceBuilder.from(0).size(5);
// 6. Highlight name field
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("name").preTags("<span style='color:red;'>").postTags("</span>");
sourceBuilder.highlighter(highlightBuilder);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse.getHits().getTotalHits().value);
for (SearchHit hit : searchResponse.getHits().getHits()) {
System.out.println("Score:" + hit.getScore());
System.out.println("Index:" + hit.getIndex());
System.out.println("ID:" + hit.getId());
for (Map.Entry<String, Object> entry : hit.getSourceAsMap().entrySet()) {
System.out.println(entry.getKey() + "--" + entry.getValue());
}
}
}5. Summary
The typical workflow is: create request → set request parameters (rules, data, etc.) → invoke the corresponding client method → receive response → extract needed information such as source or status.
Key Points
If no document ID is specified, Elasticsearch generates a random one.
Avoid hard‑coding index names; use constants or enums for maintainability.
Elasticsearch version must match the client library version.
Elasticsearch is memory‑intensive; run it on a server with sufficient RAM.
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 Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
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.
