Implementing Search Functionality with Spring Data Elasticsearch

Hello, Java developers! In this post, we will learn how to integrate Elasticsearch with Spring Boot to implement search functionality in your applications. Elasticsearch is a distributed, RESTful search and analytics engine capable of solving a wide variety of use cases, from full-text search to complex analytics.

What is Elasticsearch?

Elasticsearch is an open-source search engine built on top of the Lucene library. It provides an easy way to store, search, and analyze large volumes of data in near real-time. Its high performance and scalability make it suitable for use cases like application search, logging analysis, and business intelligence.

Why Use Elasticsearch with Spring Boot?

  • Fast Full-Text Search: Quickly retrieve relevant documents through full-text queries.
  • Scalability: Easily scale as your data grows.
  • Integration: Spring Data Elasticsearch offers seamless integration with Spring Boot, allowing you to leverage Spring’s features with Elasticsearch.
  • Powerful Query DSL: A comprehensive query DSL lets you build complex queries to suit various scenarios.

Setting Up Spring Boot with Elasticsearch

Let’s implement a Spring Boot application that integrates with Elasticsearch.

Step 1: Create a Spring Boot Project

Use Spring Initializr to create a new project. Include the following dependencies:

  • Spring Web
  • Spring Data Elasticsearch

Step 2: Add Dependencies

Your pom.xml file should look like this:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Configuring Elasticsearch Connection

In the application.properties file, you can configure the connection to your Elasticsearch instance:

spring.data.elasticsearch.rest.uris=http://localhost:9200

This assumes that you have an Elasticsearch instance running locally on the default port 9200.

Creating an Elasticsearch Document Class

Define a simple document class that will represent the data in Elasticsearch. Let’s use a Product entity:

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "products")
public class Product {
    @Id
    private String id;
    private String name;
    private double price;

    // Constructors, getters, and setters
    public Product() {}

    public Product(String id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    // Getters and Setters
}

This class is annotated with @Document, allowing Spring Data to recognize it as a document that will be stored in Elasticsearch.

Creating a Repository Interface

Create a repository interface for managing data access to the Product document:

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface ProductRepository extends ElasticsearchRepository<Product, String> {
    List<Product> findByName(String name);
}

The ProductRepository extends ElasticsearchRepository, enabling easy access to find and save Product documents.

Creating a REST Controller

Finally, create a REST controller that exposes endpoints for product operations:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @GetMapping
    public List<Product> getAllProducts() {
        return (List<Product>) productRepository.findAll();
    }

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productRepository.save(product);
    }

    @GetMapping("/search")
    public List<Product> findByName(@RequestParam String name) {
        return productRepository.findByName(name);
    }
}

This ProductController enables users to create and retrieve products as well as search for products by name.

Testing the Application

Run the Spring Boot application and test your API with Postman:

  • GET http://localhost:8080/products – Retrieve all products.
  • POST http://localhost:8080/products – Create a new product with JSON body:
  • {
        "id": "1",
        "name": "Test Product",
        "price": 9.99
    }
  • GET http://localhost:8080/products/search?name=Test Product – Search for products by name.

Best Practices for Using Spring Data Elasticsearch

  • Index Management: Set up your Elasticsearch indices properly to optimize search performance.
  • Implement Error Handling: Ensure proper handling of possible errors during requests to Elasticsearch.
  • Monitor Query Performance: Track performance metrics for your queries to identify bottlenecks.

Conclusion

Integrating Spring Boot with Apache Elasticsearch allows you to implement powerful search features in your applications. By leveraging Spring Data Elasticsearch, you can simplify the interaction with the Elasticsearch service, providing users with a rich and efficient search experience.

Want to learn more about Java Core? Join the Java Core in Practice course now!

To learn more about ITER Academy, visit our website.

Scroll to Top