Elasticsearch from Spring Boot
Wire the client, map the entity, and know when to drop to a native query.
Open this lesson in the learning hubKey points
spring-boot-starter-data-elasticsearchbrings in the official Java API client and repositories.- Spring Data Elasticsearch 5 dropped
RestHighLevelClient; the client isco.elastic.clients. - Point it with
spring.elasticsearch.uris, which defaults tohttp://localhost:9200. @Documentnames the index,@Idmarks the id field,@Fieldsets 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.