Master Elasticsearch CRUD and Advanced Queries with Spring Boot 2.3
This tutorial demonstrates how to configure Spring Boot 2.3 with Elasticsearch 7.8, covering required Maven dependencies, creating a high‑level REST client, and providing complete Java examples for index management, document CRUD, bulk operations, and a variety of advanced search techniques including pagination, sorting, filtering, range, highlighting, aggregations, and grouping.
Environment: springboot2.3.10 + elasticsearch7.8.0
Related Dependencies
<code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency></code>Index Operations
High‑level Rest client object
<code>private static RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
</code>1. Create Index
<code>public static void createIndex(String index) throws Exception {
CreateIndexRequest request = new CreateIndexRequest(index);
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
boolean ack = response.isAcknowledged();
System.out.println("ack = " + ack);
}
</code>2. View Index
<code>public static void viewIndex(String index) throws Exception {
GetIndexRequest request = new GetIndexRequest(index);
GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
System.out.println("aliases: " + response.getAliases() + "\n" +
"mappings: " + response.getMappings() + "\n" +
"settings: " + response.getSettings());
}
</code>3. Delete Index
<code>public static void deleteIndex(String index) throws Exception {
DeleteIndexRequest request = new DeleteIndexRequest(index);
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println("ack: " + response.isAcknowledged());
}
</code>Document Operations
1. Create Document
<code>public static void createDoc(String index, Users users) throws Exception {
IndexRequest request = new IndexRequest();
// Set index and unique ID
request.index(index).id("1001");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(users);
// Add document data in JSON format
request.source(jsonString, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println("_index: " + response.getIndex() + "\n" +
"_id: " + response.getId() + "\n" +
"_result: " + response.getResult());
}
</code>2. Update Document
<code>public static void updateDoc(String index, String id) throws Exception {
UpdateRequest request = new UpdateRequest();
// Configure update parameters
request.index(index).id(id);
Map<String, Object> source = new HashMap<>();
source.put("sex", "女");
request.doc(source, XContentType.JSON);
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
System.out.println("_index: " + response.getIndex() + "\n" +
"_id: " + response.getId() + "\n" +
"_result: " + response.getResult());
}
</code>3. View Document
<code>public static void viewDoc(String index, String id) throws Exception {
GetRequest request = new GetRequest().index(index).id(id);
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println("_index: " + response.getIndex() + "\n" +
"_type: " + response.getType() + "\n" +
"_id: " + response.getId() + "\n" +
"source: " + response.getSourceAsString());
}
</code>4. Delete Document
<code>public static void deleteIndex(String index, String id) throws Exception {
DeleteRequest request = new DeleteRequest().index(index).id(id);
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
System.out.println(response.toString());
}
</code>5. Bulk Operations
<code>public static void batchOperator(String index) throws Exception {
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index(index).id("1002").source(XContentType.JSON, "name","老六", "sex","男", "age", 20));
request.add(new IndexRequest().index(index).id("1003").source(XContentType.JSON, "name","外网", "sex","女", "age", 10));
request.add(new IndexRequest().index(index).id("1004").source(XContentType.JSON, "name","莉莉", "sex","女", "age", 35));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
System.out.println("took: " + response.getTook() + "\n" +
"items: " + new ObjectMapper().writeValueAsString(response.getItems()));
}
</code>Advanced Queries
6. Match All Search
<code>public static void highSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchAllQuery());
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
</code>7. Term Exact Query
<code>public static void highTermSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.termQuery("age", "20"));
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
</code>8. Pagination Query
<code>public static void highPagingSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchAllQuery());
builder.from(1);
builder.size(2);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
</code>9. Pagination & Sorting Query
<code>public static void highPagingAndSortSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchAllQuery());
builder.from(0);
builder.size(20);
builder.sort("age", SortOrder.ASC);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
</code>10. Pagination, Sorting & Field Filtering Query
<code>public static void highPagingAndSortAndFilterFieldSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchAllQuery());
builder.from(0);
builder.size(20);
builder.sort("age", SortOrder.ASC);
String[] includes = {"name"};
String[] excludes = {};
builder.fetchSource(includes, excludes);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
</code>11. Range Query
<code>public static void highBoolSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchAllQuery());
builder.from(0);
builder.size(20);
builder.sort("age", SortOrder.ASC);
RangeQueryBuilder rangeBuilder = QueryBuilders.rangeQuery("age");
rangeBuilder.gte(15);
rangeBuilder.lte(30);
builder.query(rangeBuilder);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
</code>12. Highlight Query
<code>public static void highHighLightSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchQuery("name", "莉莉"));
HighlightBuilder highLightBuilder = new HighlightBuilder();
highLightBuilder.preTags("<font color='red'>");
highLightBuilder.postTags("</font>");
highLightBuilder.field("name");
builder.highlighter(highLightBuilder);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString() + "\n" + "highlight: " + hit.getHighlightFields());
}
}
</code>13. Aggregation Query
<code>public static void highAggsSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.aggregation(AggregationBuilders.avg("avg_age").field("age"));
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
System.out.println(((ParsedAvg)response.getAggregations().iterator().next()).getValue());
}
</code>14. Group By Query
<code>public static void highGroupSearch(String index) throws Exception {
SearchRequest request = new SearchRequest().indices(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println("took: " + response.getTook() + "\n" +
"timeout: " + response.isTimedOut() + "\n" +
"total: " + hits.getTotalHits() + "\n" +
"MaxScore: " + hits.getMaxScore());
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
System.out.println(response);
}
</code>End of tutorial.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
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.