Elasticsearch Integration with Spring Boot: Dependency Setup, High‑Level Client, CRUD Operations, Bulk Processing and Search
This article provides a step‑by‑step guide on integrating Elasticsearch into a Spring Boot project, covering Maven dependency configuration, creation of a RestHighLevelClient, basic index and document CRUD operations, bulk data handling, advanced search queries with highlighting, and key implementation notes.
1. Import Elasticsearch Dependency
Add the Spring Boot Elasticsearch starter to
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>in your pom.xml. Ensure the version matches your Spring Boot version.
2. Create a High‑Level Client
Define a configuration class to expose a RestHighLevelClient bean:
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(
RestClient.builder(new HttpHost("SERVER_IP", 9200, "http")));
}
}3. Basic Usage
All CRUD operations are demonstrated with JUnit tests.
a) Index Management (Create, Exist, Delete)
@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());
}b) Document CRUD
@Test
void testAddUser() throws IOException {
User user = new User("Go", 21, new String[]{"内卷", "吃饭"});
IndexRequest request = new IndexRequest("ljx666");
request.id("6").timeout("1s");
request.source(JSONValue.toJSONString(user), XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse);
}
@Test
void testGetUser() throws IOException {
GetRequest request = new GetRequest("ljx666", "1");
GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString());
}
@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());
}
@Test
void testDeleteUser() throws IOException {
DeleteRequest request = new DeleteRequest("ljx666", "6");
DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}c) Bulk CRUD
@Test
void testBulkAddUser() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
List<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(String.valueOf(id++))
.source(JSONValue.toJSONString(u), XContentType.JSON));
}
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());
}d) Search Queries (Match All, Multi‑Match, Pagination, Highlight)
@Test
void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("ljx666");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery()); // or multiMatchQuery("java", "name")
sourceBuilder.from(0).size(5);
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() + " ID:" + hit.getId());
System.out.println(hit.getSourceAsMap());
}
}4. Summary
The typical workflow is: create a request → set request parameters (index, id, data, timeout, etc.) → invoke the corresponding client method → receive a response object → extract needed information such as source, status, or hit details.
5. Important Notes
If you do not specify an ID, Elasticsearch generates a random one.
Avoid hard‑coding index names; use constants or enums to simplify future changes.
All Elasticsearch libraries must be version‑compatible; mismatched versions cause connection failures.
Elasticsearch is memory‑intensive; run it on a server with sufficient RAM to prevent OOM kills.
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.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn 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.
