Spring Boot Integrate with Elasticsearch

·

2 min read

In this article, we will explore how to set up the elastic search as a DB, in a few simple steps.

You can go and set up a default application via start.spring.io

Once you have set up your project, you can add the following dependencies to your pom.xml file:

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

Create a configuration class to set up the Elasticsearch client:

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String esHost;

    @Value("${elasticsearch.port}")
    private int esPort;

    @Value("${elasticsearch.cluster-name}")
    private String esClusterName;

    @Bean
    public RestHighLevelClient client() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        RestClientBuilder builder = RestClient.builder(new HttpHost(esHost, esPort, "http"))
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(builder);
    }
}

In the application properties file, add the following settings to configure the Elasticsearch host and cluster name:

elasticsearch.host=localhost
elasticsearch.port=9200
elasticsearch.cluster-name=elasticsearch

Lets create a book document:

@Document(indexName = "books", type = "book")
public class Book {
    @Id
    private String id;
    private String name;
    private String author;
    private String genre;

    // getters and setters
}

Create a repository interface that extends ElasticsearchRepository:

public interface BookRepository extends ElasticsearchRepository<Book, String> {
}

Lets now create a BookService:

@Service
public class BookService {

    private final BookRepository bookRepository;

    @Autowired
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    public List<Book> findByName(String name) {
        return bookRepository.findByName(name);
    }

    public Book save(Book book) {
        return bookRepository.save(book);
    }

    public void deleteById(String id) {
        bookRepository.deleteById(id);
    }
}

Lets integrate all the components together:

@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @PostMapping
    public Book create(@RequestBody Book book) {
        return bookService.save(book);
    }
}

Now we can test the insert operation by sending a POST request to the /api/books endpoint with the book data in the request body.

For example, we can use a tool like cURL to send the request:

curl -X POST \
  http://localhost:8080/api/books \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "The Great Gatsby",
    "author": "F. Scott Fitzgerald",
    "genre": "Novel"
}'

That's all! Its that simple to integrate elasticsearch into any spring boot applications.

Feel free to share your thoughts and feedback on comments or Twitter at @smit_shah_95