Elasticsearch — a search engine for full-text search and analytics. Spring Boot connects via Spring Data Elasticsearch.
Simple analogy: Elasticsearch is like Google for your data. You ask "find all documents about Docker" — it finds them instantly, even similar ones. Unlike a database LIKE %keyword% query (which scans every row), Elasticsearch uses an inverted index — like a book's index at the back. If you search for "Docker", it jumps directly to all pages mentioning it, without reading every page.
Why it matters: Relational databases are terrible at full-text search — LIKE %keyword% cannot rank results by relevance, cannot handle synonyms, and slows down as data grows. Elasticsearch was purpose-built for this: it tokenizes text, handles fuzzy matching, supports auto-complete, and returns results ranked by relevance in milliseconds.
Configuration:
1spring:2 elasticsearch:3 uris: http://localhost:92004 username: elastic5 password: ${ES_PASSWORD}6 connection-timeout: 5s7 socket-timeout: 30s
Document:
1@Document(indexName = "articles")2public class Article {3 @Id4 private String id;56 @Field(type = FieldType.Text, analyzer = "english")7 private String title;89 @Field(type = FieldType.Text, analyzer = "english")10 private String content;1112 @Field(type = FieldType.Keyword)13 private String category;1415 @Field(type = FieldType.Date)16 private LocalDateTime publishedAt;1718 @Field(type = FieldType.Double)19 private Double score;20}
Repository + Custom Query:
1public interface ArticleRepository extends ElasticsearchRepository<Article, String> {2 List<Article> findByTitleContaining(String text);3 List<Article> findByCategoryAndPublishedAtBetween(4 String category, LocalDateTime from, LocalDateTime to);56 @Query("{"bool": {"must": [{"match": {"title": "?0"}}, {"match": {"content": "?0"}}]}}")7 List<Article> fullTextSearch(String query);89 @Query("{ "bool": { "must": [ { "match": { "content": { "query": "?0", "operator": "and" } } } ] } }")10 List<Article> searchWithAndOperator(String query);11}
ElasticsearchRepository automatically creates the index and maps objects.
Production considerations:
ElasticsearchOperations.bulkSave() for bulk inserts instead of saving one document at a time.When to use:
Do not use for transactional data — it is not a replacement for PostgreSQL.