Building Search API with ElasticSearch — Part 08: Sort results

André Coelho
2 min readJul 12, 2022

--

We are finishing creating functionality for our search API and now we are going to add the ordering feature.
Sorting results is an essential function in search engines as it will help the user to locate the items relevant to their search based on a sorting criterion.

In our movie search API we will create two sorting criteria:

  • Most popular: sort by score documents.
  • Best rating: sort by rating documents.

From these two criteria we will be able to change the ordering of the results.

Java Code

To create the sort you need to set the sort property in SearchSourceBuilder. Note that I created a SortFactory that will return which ordering will be applied when receiving the parameter.

This parameter is the SortEnum, where we declare the two sorting options:
Most Popular and Best Rating.

Running tests

In our test we are going to search for some terms and by default the order will be by Most popular then we will order by Rating and check the results

Search by term "batman":

Results by term batman

Now, set sort to Best Rating:

curl --location --request GET 'http://localhost:8080/api/movies/search?size=12&text=batman&sort=best_rating'
Results with sort Best Rating

The sort is working, the results are ordering by value rating.

We have reached the end of another post and close to the end of our series.
In the next post we will use More Like This Query to suggest suggestions for movies we have related.

Building Search API with ElasticSearch — Part 01: Preparing the environment
Building Search API with ElasticSearch — Part 02: Pagination
Building Search API with ElasticSearch — Part 03: Autocomplete
Building Search API with ElasticSearch — Part 04: Search Query
Building Search API with ElasticSearch — Part 05: Simple Facets
Building Search API with ElasticSearch — Part 06: Filters
Building Search API with ElasticSearch — Part 07: “Did you mean”
Building Search API with ElasticSearch — Part 08: Sort results
Building Search API with ElasticSearch — Part 09: Recommendation with More Like This Query
Building Search API with ElasticSearch — Part 10: Front-End
Building Search API with ElasticSearch — Part 11: Elastic APM

--

--

André Coelho

Developer of web and mobile systems. Enthusiast in the area of ​​automation and electronics and I have hobbie music.