Spring Data Solr Sorting with Example

In this article of Spring Data Solr Sorting, we will see how to sort result coming from the Solr core server. We will explore multiple mechanisms of the Sorting using Spring Boot and Spring Data Solr application.

In a word search functionality, sorting is required for the relevancy of each search result. By default, the Solr provides the resulting sorting but it allows you to implement custom sorting based on your requirement. Manually, you can set a sorting order.

Spring Data Solr Sorting

Spring Data Solr Sorting Example

This article explains how we can implement a sort of behaviour in our query results using Spring Data Solr. To achieve this we have made some changes into our example as we have implemented for previous articles such as Creating Spring Data Solr Repositories and Spring Data Solr Dynamic Queries to sort the search results in descending order by using the value of the specific field.

Specifying the Sort Options of a Query

Spring Data provides a class Sort, we can use this class to apply the sort options to the Solr queries. We can sort the query result based on the following requirements:

Using a single field for Sort the query results

Spring Data Solr allows you multiple ways to create a Sort object. This sort object specifies a query results as a sorted result by using a single field. Let’s see the following code snippet:

new Sort(Sort.Direction.DESC, "orderId")

In the above code snippet, we want to sort the query results in descending order by using the “orderId” field. Similarly, Spring Data Solr also allows you to use a value of multiple fields for sorting. Let’s in the following section.

Using multiple fields for Sort the query results with the same sort order

We can create a Sort object by taking multiple fields, the value of these fields will be used for sorting the query results. But in this case, all multiple fields are used same sorting order. Let’s see the following code snippet:

new Sort(Sort.Direction.ASC, "orderId", "orderName")

In the above code snippet, we have used the value of two fields “orderId” and “orderName” for sorting the query results in ascending order. Further, we will discuss the same thing with different sort order for the multiple fields.

Using multiple fields for Sort the query results with the different sort order

Let’s create a Sort object with multiple fields by using different sort order for each field. This sort object specifies a query results as a sorted result by using multiple fields with different sort order. Let’s see the following code snippet:

new Sort(Sort.Direction.DESC, "orderId").and(new Sort(Sort.Direction.ASC, "orderName"))

The above code snippet explains that we have used multiple fields such as “orderId” and “orderName”. The field “orderId” is using descending sorting order but “orderName” is using ascending sorting order.

Let’s move to discuss this sorting behaviour with an example.

Sorting the Query Results of Query Methods

Let’s assume we are building the Solr queries using the query methods. We can sort the query result using by passing the sort object to the query methods. There are following steps:

Step 1: Adding Sort object as sort parameter to the query method.
Step 2: Passing Sort object as sort parameter to the query method from the service layer.
Let’s see the following class that generates the query from the method name.

Query Generation From Method Name

In this step, we will explain how to create a query from the method name strategy. Let’s see the following code:

package com.doj.app.repository;

import org.springframework.data.domain.Sort;
import org.springframework.data.solr.repository.Query;
import org.springframework.data.solr.repository.SolrCrudRepository;

import java.util.List;

import com.doj.app.pojo.Order;

/**
 * @author Dinesh.Rajput
 *
 */
public interface SolrOrderRepository extends SolrCrudRepository<Order, Long> {
	
	public List findByOrderDescription(String searchTerm, Sort sort);

}

In the above code, we have created an interface SolrOrderRepository, and we have to add a Sort parameter to the findByOrderDescription() method of this interface. Let’s see sorting using @Query annotation as the following code:

Using @Query Annotation

Here we create a method annotated with the @Query annotation. Let’s see the following code:

package com.doj.app.repository;

import org.springframework.data.domain.Sort;
import org.springframework.data.solr.repository.Query;
import org.springframework.data.solr.repository.SolrCrudRepository;

import java.util.List;

import com.doj.app.pojo.Order;

/**
 * @author Dinesh.Rajput
 *
 */
public interface SolrOrderRepository extends SolrCrudRepository<Order, Long> {
	
    @Query("odesc:*?0*")
    List findByOrderDescription(String searchTerm, Sort sort);

}

In the above code, we have created a method annotated with the @Query annotation. And we have also added a Sort parameter to the findByOrderDescription() method of the SolrOrderRepository interface.

Named Queries

Let’s see the named queries method.

package com.doj.app.repository;

import org.springframework.data.domain.Sort;
import org.springframework.data.solr.repository.Query;
import org.springframework.data.solr.repository.SolrCrudRepository;

import java.util.List;

import com.doj.app.pojo.Order;

/**
 * @author Dinesh.Rajput
 *
 */
public interface SolrOrderRepository extends SolrCrudRepository<Order, Long> {
	
    @Query(name = "Order.findByNamedQuery")
    List findByNamedQuery(String searchTerm, Sort sort);

}

In the above code, we have used the named queries and we have added a Sort parameter to the findByNamedQuery() method. In the next section, we will discuss how to write a sort query for the custom repository.

Creating Custom Repository and Sorting the Query Results

Let’s see the following custom solr repository with the dynamic query creation.

package com.doj.app.repository;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.stereotype.Repository;

import com.doj.app.pojo.Order;

/**
 * @author Dinesh.Rajput
 *
 */
@Repository
public class CustomSolrOrderRepository {
	
	@Resource
    private SolrTemplate solrTemplate;
	
    public List dynamicSearch(String searchTerm) {
        Criteria conditions = createConditions(searchTerm);
        SimpleQuery search = new SimpleQuery(conditions);
         
        search.addSort(sortByOidDesc());
 
        Page results = solrTemplate.queryForPage("Order", search, Order.class);
        return results.getContent();
    }
 
    private Criteria createConditions(String searchTerm) {
        Criteria conditions = null;
 
        for (String term: searchTerm.split(" ")) {
            if (conditions == null) {
                conditions = new Criteria("oid").contains(term)
                        .or(new Criteria("odesc").contains(term));
            }
            else {
                conditions = conditions.or(new Criteria("oid").contains(term))
                        .or(new Criteria("odesc").contains(term));
            }
        }
        return conditions;
    }
 
    private Sort sortByOidDesc() {
        return new Sort(Sort.Direction.DESC, "oid");
    }
    
}

In the above code, we have added a private method sortByOddDesc() to the CustomSolrOrderRepository class and this method returns a Sort object. And finally, we have created a method search() to this class and set the sort options to the executed query by using the addSort() method of the Query interface. After that, we have passed the created Sort object as a method parameter.

Summary

In this article, we have learnt about how to create a sorted query using the Spring Data Solr Sorting and creating the custom repository with dynamic Solr queries.

Previous
Next