Big Data 17 min read

Java API for Elasticsearch: Configuration, CRUD, DSL Queries, Pagination, Sorting, and Highlighting

This article demonstrates how to integrate Elasticsearch 6.2.1 with a Spring Boot project using the high‑level REST client, covering Maven dependencies, bean configuration, index creation and deletion, various DSL queries, pagination, sorting, boosting, boolean filters, and result highlighting with complete Java code examples.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Java API for Elasticsearch: Configuration, CRUD, DSL Queries, Pagination, Sorting, and Highlighting

This guide shows how to set up a Spring Boot project to work with Elasticsearch 6.2.1 using the elasticsearch‑rest‑high‑level‑client and the low‑level RestClient.

Dependencies

<!-- ES client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>${elasticsearch.version}</version>
</dependency>
<!-- ES version -->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>${elasticsearch.version}</version>
</dependency>

Bean configuration

@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

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

Index operations (CRUD)

@Test
public void testDelIndex() throws IOException {
    IndicesClient indices = client.indices();
    DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("ysx_course");
    DeleteIndexResponse response = indices.delete(deleteIndexRequest);
    System.out.println(response.isAcknowledged());
}

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\": \"scaled_float\",
    \"scaling_factor\": 100
},
    \"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());
}

DSL search examples

Match all query with source filtering

{
  "query": { "match_all": {} },
  "_source": ["name", "studymodel"]
}

Term query (exact match)

{
  "query": { "term": { "name": "spring" } },
  "_source": ["name", "studymodel"]
}

Match query with

minimum_should_match
{
  "query": {
    "match": {
      "description": { "query": "spring开发", "operator": "or" }
    }
  }
}

Multi‑match query across name and description with boosting

{
  "query": {
    "multi_match": {
      "query": "Spring开发框架",
      "minimum_should_match": "70%",
      "fields": ["name^10", "description"]
    }
  }
}

Boolean query with filters

{
  "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

searchSourceBuilder.sort("studymodel", SortOrder.DESC);
searchSourceBuilder.sort("price", SortOrder.ASC);

Highlighting results

HighlightBuilder hb = new HighlightBuilder();
 hb.preTags("<em>");
 hb.postTags("</em>");
 hb.field(new HighlightBuilder.Field("name"));
 hb.field(new HighlightBuilder.Field("description"));
searchSourceBuilder.highlighter(hb);

All code snippets are kept intact inside

tags, and the article also notes common pitfalls such as missing <code>yunshangxue.elasticsearch.hostlist

placeholders and Maven project misconfiguration.

DSLElasticsearchPaginationSpringBootSearchsortinghighlighting
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

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.