Master Spring Boot & Elasticsearch Integration: Step‑by‑Step Guide with Code Samples
This tutorial walks you through creating a Spring Boot project, adding Elasticsearch 6.2.1 dependencies, configuring a RestHighLevelClient bean, setting up host properties, and performing core index operations, pagination, various query types, sorting, filtering, and highlighting using both DSL JSON and Java APIs.
Spring Boot Integration with Elasticsearch
Creating a Spring Boot project and importing the Elasticsearch 6.2.1 RestHighLevelClient and core elasticsearch dependencies. Directly using es-starter may cause container initialization errors; resolve by configuring the client manually.
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>Define RestClient Bean
@Configuration
public class ESConfig {
@Value("${yunshangxue.elasticsearch.hostlist}")
private String hostlist; // e.g., 127.0.0.1:9200
@Bean
public RestHighLevelClient restHighLevelClient() {
String[] split = hostlist.split(",");
HttpHost[] httpHostArray = new HttpHost[split.length];
for (int i = 0; i < split.length; i++) {
String item = split[i];
httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
}
return new RestHighLevelClient(RestClient.builder(httpHostArray));
}
@Bean
public RestClient restClient() {
String[] split = hostlist.split(",");
HttpHost[] httpHostArray = new HttpHost[split.length];
for (int i = 0; i < split.length; i++) {
String item = split[i];
httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
}
return RestClient.builder(httpHostArray).build();
}
}Configure ES Host in application.yml
yunshangxue:
elasticsearch:
hostlist: ${eshostlist:127.0.0.1:9200}Basic Index Operations (Java API)
Create index object
Build index request
Execute request
Obtain response
Delete Index Example
@Test
public void testDelIndex() throws IOException {
IndicesClient indices = client.indices();
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("ysx_course");
DeleteIndexResponse response = indices.delete(deleteIndexRequest);
boolean acknowledged = response.isAcknowledged();
System.out.println(acknowledged);
}Create Index Example (with Mapping)
public void testAddIndex() throws IOException {
IndicesClient indices = client.indices();
CreateIndexRequest request = new CreateIndexRequest("ysx_course");
request.settings(Settings.builder()
.put("number_of_shards", "1")
.put("number_of_replicas", "0"));
request.mapping("doc", "{
" +
\"properties\": {
" +
\"description\": {
" +
\"type\": \"text\",
" +
\"analyzer\": \"ik_max_word\",
" +
\"search_analyzer\": \"ik_smart\"
},
" +
\"name\": {
" +
\"type\": \"text\",
" +
\"analyzer\": \"ik_max_word\",
" +
\"search_analyzer\": \"ik_smart\"
},
" +
\"pic\":{
" +
\"type\":\"text\",
" +
\"index\":false
},
" +
\"price\": {
" +
\"type\": \"float\"
},
" +
\"studymodel\": {
" +
\"type\": \"keyword\"
},
" +
\"timestamp\": {
" +
\"type\": \"date\",
" +
\"format\": \"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis\"
}
}
}", XContentType.JSON);
CreateIndexResponse response = indices.create(request);
boolean acknowledged = response.isAcknowledged();
System.out.println(acknowledged);
}DSL Search
DSL (Domain Specific Language) is a JSON‑based query language that offers richer capabilities than simple URI queries.
Match All Query
POST http://localhost:9200/ysx_course/doc/_search
{
"query": { "match_all": {} },
"_source": ["name","studymodel"]
}Pagination Query
{
"from": 0,
"size": 1,
"query": { "match_all": {} },
"_source": ["name","studymodel"]
}Term Query (Exact Match)
{
"query": { "term": { "name": "spring" } },
"_source": ["name","studymodel"]
}Match Query (Full‑text)
{
"query": {
"match": {
"description": {
"query": "spring开发",
"operator": "or"
}
}
}
}Multi‑Match Query (Multiple Fields)
{
"query": {
"multi_match": {
"query": "Spring开发框架",
"minimum_should_match": "70%",
"fields": ["name","description"]
}
}
}Bool Query (Combined Conditions)
{
"query": {
"bool": {
"must": [
{ "multi_match": { "query": "spring框架", "minimum_should_match": "50%", "fields": ["name^10","description"] } },
{ "term": { "studymodel": "201001" } }
],
"filter": [
{ "term": { "studymodel": "201001" } },
{ "range": { "price": { "gte": 60, "lte": 100 } } }
]
}
}
}Sorting
{
"query": { "match_all": {} },
"sort": [
{ "studymodel": "desc" },
{ "price": "asc" }
]
}Highlighting
{
"query": { "match": { "description": { "query": "开发框架" } } },
"highlight": {
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"fields": { "name": {}, "description": {} }
}
}All examples are wrapped in JUnit @Test methods; the search results can be processed by iterating over SearchHit objects, extracting fields, applying highlights, and formatting timestamps as needed.
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.
