Elasticsearch from Spring Boot

Elasticsearch Course · lesson 14 of 19 · 5 min read

Wire the client, map the entity, and know when to drop to a native query.

Open this lesson in the learning hub

Key points

  • spring-boot-starter-data-elasticsearch brings in the official Java API client and repositories.
  • Spring Data Elasticsearch 5 dropped RestHighLevelClient; the client is co.elastic.clients.
  • Point it with spring.elasticsearch.uris, which defaults to http://localhost:9200.
  • @Document names the index, @Id marks the id field, @Field sets the type.
  • Derived repository methods cover the easy cases; anything scored or aggregated needs a native query.
  • Since 8.0 security is on by default, so plain http fails until TLS and credentials are configured.

Example

@Document(indexName = "articles")
public class Article {
    @Id private String id;

    @Field(type = FieldType.Text, analyzer = "english")
    private String title;

    @Field(type = FieldType.Keyword)
    private String status;

    @Field(type = FieldType.Date, format = DateFormat.date_time)
    private Instant publishedAt;
}

public interface ArticleRepo extends ElasticsearchRepository<Article, String> {
    List<Article> findByStatus(String status);
}

// scoring, aggregations, highlighting -> drop to the operations API
NativeQuery q = NativeQuery.builder()
    .withQuery(qb -> qb.match(m -> m.field("title").query(text)))
    .build();
SearchHits<Article> hits = operations.search(q, Article.class);

Let the starter build the client, annotate the entity properly, and use NativeQuery for real search.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Elasticsearch Course course, and every lesson in it is listed on the Elasticsearch Course contents page.