How to generate an advanced search API in Spring Boot in 5 minutes

2
minutes
Mis à jour le
15/9/2019

Share this post

In this article, you will learn how to use the spring-search library to provide search endpoints to your JPA entities in Spring Boot.

#
Kotlin
#
Open Source
#
Spring Boot

We just released our first open source library : Spring-search.

Spring-search provides a simple yet advanced query language to perform searches on a JPA entity.

 

For example, let's say you have the following Car model :

Our example is in Java, in order to show that spring-search works on any Spring Boot project. See our Github repository for a Kotlin example.

 

And the following Options model :

 

You want to get cars whose brand is "Aston Martin" or whose price is more than 10000$ and with an automatic transmission.

With Spring-search, the query : /search=(brand:'Aston Martin' OR price>100000) AND options.transmission:Auto will provide the desired result.

How do I install spring-search in my Spring Boot project ?

In Maven projects, simply add the repo to your project inside your pom.xml file.

<dependency>
    <groupId>com.sipios</groupId>
    <artifactId>spring-search</artifactId>
    <version>0.2.0</version>
</dependency>

In Gradle projects, add implementation 'com.sipios:spring-search:0.2.0' in your build.gradle file.

For other types of projects, see https://search.maven.org/artifact/com.sipios/spring-search/0.2.0/jar.

How do I use spring-search once it is installed ?

 

Your repository should be annotated as a RepositoryRestResource and should extend JpaSpecificationExecutor

Import the library in your controller and use it in the following way

 

The previous query returns the following result :

example-query

What operations are possible in my queries ?

  • The equal operation, using the : operator
  • The not equal operation, using the ! operator
  • The greater than and less than operators, respectively > and <
  • The starts with/ends with/contains operator, using *. It acts like the bash * expension.
  • The AND operator.
  • The OR operator.
  • Parenthesis can be used for grouping.
  • You can access a deep field of an object using the . notation. For instance options.transmission in our example.

For usage examples, see our Github repository for the project.

I'd like a new feature, where can I ask for it ?

We'd love to hear new ideas for this project!

Feel free to create an issue on our Github issues page. Or you can even create a Pull Request on the repository, they will be greatly appreciated.