Search is one of the pillars of the web, and full-text search is one of the mandatory features that every website needs. But implementing such a feature is complex, and lots of skilled engineers have already thought hard about this topic. So let’s not reinvent the wheel, and use the battle-tested Hibernate Search library.
In this blog post, we are going to learn how to build a simple REST API endpoint in Spring boot with full-text search using Hibernate Search. We will only go through the basics, but Hibernate Search is a feature-rich library with many features going way beyond what we will see in this post. You can check everything that it provides in the official documentation https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#gettingstarted-framework.
Project Bootstrap
The first step is to generate the spring boot project using spring initializr. In this tutorial, We are using the spring CLI via SDKman, but it can easily be done using the web UI https://start.spring.io/ or directly through your IDEA https://www.jetbrains.com/help/idea/spring-boot.html.
To have a walkthrough of how to set up the CLI on your own machine, follow this guide https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started.html#getting-started.installing.cli.sdkman. Once you have installed the CLI , execute this command to generate the project with the necessary dependencies.
|
|
We package the following dependencies :
- the web dependency for the REST API.
- the spring data JPA for the data access layer, which uses hibernate as the default Object Relational Mapping tool.
- the h2 library to provide an easy-to-use in-memory embedded database. This type of database is suited for small toy projects such as this one, but it should not be used for any serious project that will be shipped to production at some point.
- Lombok to generate snippets of code through annotation and avoid any boilerplate code
- validation is the Hibernate implementation of the validation API that follows the JSR 380 specification. It allows, among other things, to validate beans using annotation.
Hibernate Search Setup
As with many libraries, Spring Boot provides an easy way to integrate Hibernate Search. We just need to add the required dependencies into the pom.xml file.
|
|
We are using hibernate search 6 which is the most recent version to date, with Lucene as the backend. Lucene is an open-source indexing and search engine library, and the default implementation used by Hibernate Search. We could also use different implementations such as ElasticSearch or OpenSearch.
Defining the data model
The first step is to define the model of the entity on which the search will be done.
As an example, we will use a Plant entity, containing the plant’s common name, scientific name, family, and date of creation.
|
|
Let’s ignore the JPA and Lombok annotations, and focus on the Hibernate Search-related ones.
First, the @index annotation indicates to Hibernate Search that we want to index this entity in order to apply search operation on it.
Second, we annotate the fields we want to search on with the @FullTextField annotation. This annotation works only for string fields, but others exist for fields of different types.
And … that’s it! It is as simple as that for a simple case such as ours!
But you can do much more with what the library provides, such as using conditional indexing or tweaking indexing coordination. Once again, check out the official documentation if you want to know more.
Defining the data layer
We now need to define our data layer handling the interactions with the database.
We use Spring Data repositories which build an abstraction around the Hibernate implementation of JPA. It is provided in the spring-boot-starter-data-jpa
dependency added previously.
For a basic use case requiring only CRUD operations, we can define a simple repository for the Plant entity and extends the JpaRepository interface directly.
But this is not enough for full-text search. In our case, we would like to add the search features to all repositories we define. For that, we need to add custom methods to the JpaRepository interface, or any interface extending the base Repository
interface.
This way, we declare those methods only once and make them available for every repository of every entity of our project.
Let’s see how we can do such a thing.
First, we need to create a new generic interface that extends the JpaRepository interface.
We declare the searchBy function that will be used for full-text search operations.
The @NoRepositoryBean annotation tells spring that this repository interface should not be instantiated like any other bean with the @Repository annotation.
We use this annotation because the purpose of this interface is not to be used directly, but to be implemented by other repositories.
We also need to create the implementation for this interface.
|
|
The searchBy method implementation is where Hibernate Search is used.
The following arguments are passed:
- text: text to search for
- limit: maximum number of elements to search for
- fields: name of all the fields to search on
We make use of java varargs to pass all the fields we want to search on.
Here, we use a simple fuzzy algorithm as the full-text matching algorithm, but we can easily make more complex searches using custom analyzers.
From now on, repositories requiring full-text-search just have to implement the SearchRepository interface instead of the standard JpaRepository interface provided by Spring.
And this is exactly what we are doing for the Plant entity.
As you can see, all implementation is already done, and we just need to implement the previously created SearchRepository interface to get access to the implementation defined in the SearchRepositoryImpl class.
The final step is to indicate to Spring to detect Jpa Repositories using the SearchRepositoryImpl as the base class.
|
|
Note that because we do not specify any base package to search into, Spring will use the package where this Configuration is defined as the base package.
Defining the business layer
Let’s now create the business code using the data layer we’ve just defined, by declaring a service.
|
|
We tell Spring that this bean is part of the business layer of the application.
It contains a searchPlant function that forwards the call to the searchBy function of the SearchRepository.
Before forwarding the call, it validates the provided fields.
Those fields are whitelisted to check that the search will be made only against the desired fields, which are the ones we have annotated with @FullTextField annotation earlier.
We throw an IllegalArgumentException if one of the provided fields is not part of the whitelisted ones. The exception is not handled for the sake of simplicity, but it should be handled properly using one of the many ways provided by spring to handle exceptions.
Defining the web layer
The next step is to define the REST API to receive the HTTP request coming from client applications.
|
|
We use a basic Rest controller with a single GET mapping. Before forwarding the call to the business layer, we log the event to trace the reception of the request to ease the monitoring of the application. It receives the search request using a SearchRequestDTO
|
|
It is a simple POJO containing the parameters used for the search. Once again, we use Javax Bean Validation annotations to ensure the request is valid, as well as Lombok @data annotation to generate boilerplate code (Getters, Setters, toString(), …).
Note that by using a POJO as a single argument for the REST API endpoint, we expect the client to send those parameters as Request Parameter inside the HTTP request.
Indexing the data
Finally, for Lucene to be able to search through the data, it needs to be indexed.
At runtime, the index is automatically managed by Hibernate, by applying the change each time an operation is executed through Hibernate ORM such as creating or deleting an Entity. However, We still need to initialize the index for data already stored in the database if any.
For that purpose, we need to add some configurations inside the application.yml file:
We indicate the root directory of where the Lucene index is stored. Here, we choose to place it directly in the project folder, but this directory should be carefully chosen when running in production, depending on where your application is deployed.
We also create a component to wrap all operations related to the Lucene index.
|
|
For our simple demo application, we only declare a function that builds the index for a given Class using the specified amount of threads in the process.
We now need to call that function passing the previously defined Plant class as an argument.
For that purpose, we could also create a new REST Controller containing an endpoint to trigger the indexing via an HTTP request, to be able to rebuild the index at will.
But for the sake of this article, we are just going to use an ApplicationRunner that will be called at each startup.
|
|
We define the Bean directly in the main Application class.
The buildIndex method takes the Indexer as an argument through dependency injection. The method is executed during the application startup, right after the context initialization, and before the startup of the spring boot application.
Putting it all together
Let’s first initialize the sample data.
|
|
We extend the main Application class with a second Bean declaration. It will be run in the same way as the first one, during the application startup.
Note that we did not declare the data SQL schema anywhere. Because our database is an embedded database, the property spring.jpa.hibernate.ddl-auto is set to create-drop by default, and our database schema is automatically generated, which is neat for simple applications such as this one.
Now, let’s test, by first starting our application.
|
|
There are multiples ways to test the search endpoint.
We can use the API Platform Postman:
Or we can use a simple cUrl command with the required parameters :
And that’s it! We now have full-text-search implemented through an HTTP endpoint.
As I’ve said many times during this blog, Hibernate Search provides much more features, and we’ve just scratched the surface here.
I will publish more blog posts to address more advanced topics soon.
You can access the demo project for this blog post here https://github.com/Mozenn/spring-boot-hibernate-search.
Reference https://dev.to/mozenn/build-a-spring-boot-rest-api-with-full-text-search-using-hibernate-search-4a67