Integrating Spring Boot with Elasticsearch Using Java API

This tutorial explains how to set up a Spring Boot project with Elasticsearch 6.2.1, configure RestHighLevelClient and RestClient beans, define ES host settings, and perform index creation, deletion, pagination, various query types, sorting, and highlighting through the Java API.

Architecture Digest
Architecture Digest
Architecture Digest
Integrating Spring Boot with Elasticsearch Using Java API

This article demonstrates how to integrate Spring Boot with Elasticsearch 6.2.1, covering project initialization, Maven dependencies, and bean configuration for both RestHighLevelClient and RestClient.

It shows how to specify the Elasticsearch host list in application.yml and provides complete Java code for creating, deleting, and searching indices using the Elasticsearch Java API.

<!-- ES client dependency -->
<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>

Configuration class defining the two client beans:

@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();
    }
}

YAML configuration for the host list:

yunshangxue:
  elasticsearch:
    hostlist: ${eshostlist:127.0.0.1:9200}

Typical CRUD operations are illustrated with JUnit tests. For example, deleting an index:

@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);
}

Creating an index with mapping and settings:

@Test
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\"
" +
        \"    },
" +
        \"    \"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);
    System.out.println(response.isAcknowledged());
}

Various query types are covered:

MatchAll query for retrieving all documents.

TermQuery for exact matches (e.g., studymodel).

MatchQuery with minimum_should_match for controlled relevance.

MultiMatchQuery to search across multiple fields.

BoolQuery combining must, should, and filter clauses.

Range filters for numeric or date fields.

Sorting results by keyword or numeric fields.

Highlighting matched terms with custom pre/post tags.

Example of a Bool query with filters:

{
  "query": {
    "bool": {
      "must": [
        { "multi_match": { "query": "spring框架", "minimum_should_match": "50%", "fields": ["name^10", "description"] } }
      ],
      "filter": [
        { "term": { "studymodel": "201001" } },
        { "range": { "price": { "gte": 60, "lte": 100 } } }
      ]
    }
  },
  "sort": [ { "studymodel": "desc" }, { "price": "asc" } ],
  "highlight": {
    "pre_tags": ["<em>"],
    "post_tags": ["</em>"],
    "fields": { "name": {}, "description": {} }
  }
}

Corresponding Java API usage shows how to build the same query with QueryBuilders, set sorting via searchSourceBuilder.sort(...), and enable highlighting with HighlightBuilder. The article also discusses pagination parameters ( from and size) and how to retrieve total hits versus returned hits.

Overall, the guide provides a comprehensive, code‑first reference for developers who need to connect Spring Boot applications to Elasticsearch, covering configuration, CRUD, advanced search features, and best practices.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaElasticsearchSpringBootREST APISearch
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.