Master Spring Boot Elasticsearch Integration: Build, Index, Search, and Analyze Data
This tutorial walks through using Spring Boot with Elasticsearch's Java High Level REST Client, covering project setup, dependency configuration, client creation, index mapping, data insertion, various search techniques, and aggregation analysis, all with complete code examples.
Today we will explain how to operate Elasticsearch in a Spring Boot project using the official Java High Level REST Client v7.9.1. It assumes basic Java backend knowledge and Spring Boot.
8.1 Preparation
Download the source code from Gitee, import as a standard Spring Boot project. Packages:
boot.spring.config : global configuration such as CORS.
boot.spring.controller : REST controllers.
boot.spring.elastic.client : Elasticsearch client configuration.
boot.spring.elastic.service : services for creating indices, searching, and aggregations.
boot.spring.pagemodel : DTOs for the front‑end.
boot.spring.po : index field POJOs.
boot.spring.util : utility classes.
Add the following dependencies to pom.xml:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.9.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.9.1</version>
</dependency>The Client class reads es.url from application.yml, splits multiple nodes, and builds a RestHighLevelClient.
8.2 Create Index and Import Data
8.2.1 Mapping
Custom analyzer for sougoulog
In IndexController the createMapping method builds a JSON mapping with XContentBuilder. The mapping defines a custom analyzer my_analyzer and applies it to fields keywords, url, userid. The service method createMapping sends a CreateIndexRequest to Elasticsearch.
Geo‑point mapping for shop
Similar code creates a shop index with a location field of type geo_point.
Nested object mapping for city
The city index contains a nested country object.
Join field mapping for cityjoincountry
Defines a parent‑child relationship using a join field.
8.2.2 Data Insertion
Two ways to write documents:
JSON string via IndexRequest.source(json, XContentType.JSON).
HashMap via IndexRequest.source(map).
Batch insertion uses BulkRequest and loops over a list of maps.
Routing is required for join documents; the routing method sets the route on the request.
Updates use UpdateRequest with docAsUpsert(true) to achieve upsert behavior.
Deletions use DeleteRequest and handle possible version conflicts.
8.3 Search Data
Common Boolean query example:
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder bool = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("name", "zhangsan"))
.filter(QueryBuilders.rangeQuery("born").from("2010-01-01").to("2011-01-01"));
builder.query(bool);
searchRequest.source(builder);Search methods include:
Multi‑text field search with queryStringQuery and optional filters.
Geo‑distance search using geoDistanceQuery.
Nested object search with nestedQuery.
Parent‑to‑child search via hasParentQuery.
Child‑to‑parent search via hasChildQuery.
Results can be retrieved as maps, JSON strings, or highlighted fragments.
8.4 Aggregations
Examples:
Terms aggregation:
AggregationBuilders.terms("countnumber").field(field).size(10).order(BucketOrder.key(true)).
Date histogram:
AggregationBuilders.dateHistogram("aggsName").field(dateField).fixedInterval(DateHistogramInterval.seconds(step)).minDocCount(0L).
Date range:
AggregationBuilders.dateRange("aggsName").field(dateField).addUnboundedFrom(...).addRange(...).
Nested aggregation:
AggregationBuilders.nested("nestedAggs","country").subAggregation(AggregationBuilders.terms("groupbycountry").field("country.countryname.keyword").size(100)).
Each aggregation result is extracted from SearchResponse.getAggregations() and iterated over the buckets.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
