Spring Boot + Elasticsearch: Full-Text Search Integration
Introduction
In today’s data-driven world, users expect instant, relevant search results—whether they’re searching for products, documents, or log entries. Traditional relational databases fall short when it comes to full-text search: they struggle with fuzzy matching, stemming, synonyms, and ranking by relevance. This is where Elasticsearch shines.
Elasticsearch is a distributed, RESTful search engine built on Apache Lucene. It provides near real-time search, powerful aggregations, and scalability out of the box. When combined with Spring Boot, you get a robust foundation for building modern applications with seamless search capabilities.
In this guide, I’ll walk you through integrating Elasticsearch into a Spring Boot application, from setup to advanced query building. We’ll cover:
- Setting up Elasticsearch locally or via Docker
- Adding the necessary dependencies
- Creating an index and mapping
- Performing CRUD operations
- Implementing full-text search queries
- Handling pagination, sorting, and highlighting
- Best practices for performance and maintainability
By the end, you’ll have a solid understanding of how to leverage Elasticsearch in your Spring Boot projects.
Prerequisites
Before diving in, ensure you have:
- Java 11 or later
- Maven or Gradle
- Docker (optional but recommended for running Elasticsearch)
- Basic knowledge of Spring Boot and REST APIs
Setting Up Elasticsearch
Option 1: Using Docker (Recommended)
Docker is the easiest way to get Elasticsearch running locally. Create a docker-compose.yml file:
1 | version: '3.8' |
Then run:
1 | docker-compose up -d |
Option 2: Local Installation
Download and extract Elasticsearch from elastic.co/downloads/elasticsearch. Then run:
1 | ./bin/elasticsearch |
Once running, verify it’s up by hitting http://localhost:9200. You should see a JSON response with the version info.
Creating a Spring Boot Project
Head to Spring Initializr and generate a project with the following dependencies:
- Spring Web
- Spring Data Elasticsearch
- Lombok (optional)
Alternatively, add these to your pom.xml:
1 | <dependency> |
Configuration
In application.yml, configure the Elasticsearch connection:
1 | spring: |
For more advanced settings (like authentication), you can use RestClientBuilder or ElasticsearchClient beans. Spring Boot auto-configures a RestClient and ElasticsearchOperations bean for you.
Defining an Entity
We’ll create a simple Product entity that we want to index and search.
1 | import org.springframework.data.annotation.Id; |
Key annotations:
@Documentmarks the class as an Elasticsearch document and specifies the index name.@Fielddefines the field mapping.Textis analyzed for full-text search, whileKeywordis exact-match only.
Repository Layer
Spring Data Elasticsearch provides a repository abstraction similar to Spring Data JPA. Create an interface:
1 | import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; |
This gives you basic CRUD operations out of the box. But for full-text search, we’ll need custom queries.
Building a Search Service
Let’s create a service that uses ElasticsearchOperations (or ElasticsearchClient) to build dynamic queries.
1 | import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate; |
But this is still basic. For true full-text search, we need to use match queries and other full-text query types.
Implementing Full-Text Search
Full-text search in Elasticsearch uses analyzers to tokenize and normalize text. The match query is the standard for full-text search.
Using MatchQuery
1 | import org.springframework.data.elasticsearch.core.query.Criteria; |
Multi-Field Search
Often, you want to search across multiple fields with different weights. Use MultiMatchQueryBuilder:
1 | import org.springframework.data.elasticsearch.core.query.MultiMatchQueryBuilder; |
Using NativeQuery for Advanced Queries
For complex queries, you can use NativeQuery with the Elasticsearch query DSL:
1 | import co.elastic.clients.elasticsearch._types.query_dsl.Query as EsQuery; |
Pagination and Sorting
For real-world applications, you need to paginate results. Spring Data Elasticsearch integrates with Spring Data’s Pageable:
1 | import org.springframework.data.domain.PageRequest; |
For sorting, add a Sort to the query:
1 | import org.springframework.data.domain.Sort; |
Highlighting Search Terms
Highlighting shows the matched terms in the results, which improves user experience. Here’s how to add highlighting:
1 | public List<Map<String, Object>> searchWithHighlights(String text) { |
Advanced Query Types
Fuzzy Search
To handle typos, use fuzzy matching:
1 | query.withQuery(q -> q |
Phrase Search
To match exact phrases:
1 | query.withQuery(q -> q |
Boolean Queries
Combine multiple conditions with boolean logic:
1 | query.withQuery(q -> q |
Best Practices
- Design your index mapping carefully – Decide which fields are
text(analyzed) and which arekeyword(exact). Over-analyzing keywords can lead to performance issues. - Use custom analyzers for language-specific stemming and stop words.
- Leverage Spring Data’s repository for simple queries, but use
ElasticsearchOperationsfor complex ones. - Handle connection retries – Elasticsearch might temporarily be unavailable. Configure
RestClientwith retry logic. - Monitor performance – Use Elasticsearch’s
_searchprofiling and slow logs. - Avoid N+1 queries – When fetching related documents, use bulk operations or
mget. - Keep entities lightweight – Don’t map all fields if you don’t need them in search.
Testing the Integration
Write a simple REST controller to test:
1 |
|
You can test with curl:
1 | curl -X POST http://localhost:8080/api/products -H "Content-Type: application/json" -d '{"name":"Wireless Mouse","description":"Ergonomic wireless mouse with USB receiver","category":"Electronics","price":29.99}' |
Conclusion
Integrating Elasticsearch with Spring Boot opens up a world of possibilities for building high-performance search features. We’ve covered the essentials: setting up Elasticsearch, creating entities, building repositories, and implementing various search queries. Remember to design your index mapping thoughtfully and leverage the full power of Elasticsearch’s query DSL for complex requirements.
With the foundation you’ve gained here, you can now explore more advanced topics like aggregations, geospatial search, and suggesters. Happy searching!
Key Takeaways
- Spring Boot + Elasticsearch provides a seamless way to add full-text search to your applications.
- Use
@Documentand@Fieldannotations to define your index mapping. ElasticsearchRepositoryoffers basic CRUD, whileElasticsearchOperationsgives you fine-grained control over queries.- Match queries are the go-to for full-text search; use multi-match for searching across fields.
- Leverage
NativeQueryfor complex boolean and advanced queries. - Pagination and sorting are easily integrated with Spring Data’s
PageableandSort. - Highlighting improves user experience by showing matched terms.
- Always design your index mapping with performance and relevance in mind.