Step-by-Step Guide to Using Elasticsearch in a Spring Boot Application
Introduction
Elasticsearch is a highly scalable, open-source search and analytics engine that enables you to store, search, and analyze large volumes of data quickly and in near real-time. In this tutorial, we will learn how to integrate Elasticsearch with a Spring Boot application to improve search functionality in our applications. We’ll walk through the process step-by-step, providing code samples along the way to make it easy to understand and implement.
Prerequisites
- Java 8 or higher
- Spring Boot 2.6.0 or higher
- Maven or Gradle (for building the project)
Step 1: Create a Spring Boot project
First, create a new Spring Boot project using the Spring Initializr tool (https://start.spring.io/). Select the following options:
- Project type: Maven Project
- Packaging: Jar
- Java version: 8 or higher
- Dependencies: Web, Elasticsearch
Download the generated project and extract it to a folder of your choice.
Step 2: Configure Elasticsearch dependencies
Open the pom.xml
file and add the following dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.16.1</version>
</dependency>
For Gradle users, add the dependencies in build.gradle
:
implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch'
implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.16.1'
Step 3: Configure Elasticsearch connection
In the src/main/resources/application.properties
file, add the following configuration:
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9200
spring.data.elasticsearch.repositories.enabled=true
Replace localhost:9200
with your Elasticsearch server's address and port if it's running on a different machine.
Step 4: Define a model class
Create a new package com.example.elasticsearch.model
and add a class Employee
:
package com.example.elasticsearch.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "employee", shards = 1, replicas = 0, refreshInterval = "-1")
public class Employee {
@Id
private String id;
private String firstName;
private String lastName;
private String department;
// Getters and setters
}
Step 5: Create a repository interface
Create a new package com.example.elasticsearch.repository
and add an interface EmployeeRepository
:
package com.example.elasticsearch.repository;
import com.example.elasticsearch.model.Employee;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface EmployeeRepository extends ElasticsearchRepository<Employee, String> {
}
Step 6: Implement a REST controller
Create a new package com.example.elasticsearch.controller
and add a class EmployeeController
:
package com.example.elasticsearch.controller;
import com.example.elasticsearch.model.Employee;
import com.example.elasticsearch.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@Autowired
private EmployeeRepository repository;
@PostMapping
public Employee create(@RequestBody Employee employee) {
return repository.save(employee);
}
@GetMapping("/{id}")
public Optional<Employee> findById(@PathVariable String id) {
return repository.findById(id);
}
@GetMapping
public Iterable<Employee> findAll() {
return repository.findAll();
}
@PutMapping("/{id}")
public Employee update(@PathVariable String id, @RequestBody Employee employee) {
employee.setId(id);
return repository.save(employee);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable String id) {
repository.deleteById(id);
}
}
Step 7: Run the application
Start your Spring Boot application using your favorite IDE, or run the following command in the project’s root directory:
./mvnw spring-boot:run
For Gradle users:
./gradlew bootRun
Step 8: Test the RESTful API
Use a REST client, like Postman or curl, to test the API endpoints. Here are some example curl commands:
Create a new employee:
curl -X POST -H "Content-Type: application/json" -d '{"firstName": "John", "lastName": "Doe", "department": "Engineering"}' http://localhost:8080/api/employees
Retrieve an employee by ID:
curl -X GET http://localhost:8080/api/employees/{id}
Get all employees:
curl -X GET http://localhost:8080/api/employees
Update an employee:
curl -X PUT -H "Content-Type: application/json" -d '{"firstName": "Jane", "lastName": "Doe", "department": "HR"}' http://localhost:8080/api/employees/{id}
Delete an employee:
curl -X DELETE http://localhost:8080/api/employees/{id}
Conclusion
In this tutorial, we demonstrated how to integrate Elasticsearch into a Spring Boot application. We created a RESTful API to perform CRUD operations on employee records, and we leveraged Elasticsearch to store and search this data. By following this guide, you should be able to implement Elasticsearch in your own Spring Boot applications and improve the search capabilities of your projects.