How to sort search results by item SortOrder


Description

This article recommends how to sort search results by item SortOrder. Using a computed index field, you can customize sorting to show the search results in the same order as the items in the Content Tree.

Note that ordering search results by item SortOrder makes sense only if all the search results share the same parent item, meaning that the search expression includes:

.Where(item => item.Parent == parentItem.ID);

Solution

To create a custom computed index field:

  1. Create a custom class that implements the IComputedIndexField interface:
    public object ComputeFieldValue(Sitecore.ContentSearch.IIndexable indexable)
    
    {
    
      Sitecore.Data.Items.Item item = (indexable as Sitecore.ContentSearch.SitecoreIndexableItem);
    
      if ((item != null))
    
      {
    
        return item.Appearance.Sortorder;
    
      }
    
      else
    
      {
    
        return Sitecore.Configuration.Settings.DefaultSortOrder;
    
      }
    
    }
    
  2. Add the computed index field to the configuration by creating a configuration patch file in the \App_Config\Include\zzz folder:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:search="http://www.sitecore.net/xmlconfig/search/">
      <sitecore role:require="Standalone or ContentManagement or ContentDelivery" search:require="solr">
        <contentSearch>
          <indexConfigurations>
            <defaultSolrIndexConfiguration>
              <documentOptions>
                <fields hint="raw:AddComputedIndexField">
                  <field fieldName="sortOrder" returnType="int">[fully qualified class name],[custom assembly name]</field>
                </fields>
              </documentOptions>
            </defaultSolrIndexConfiguration>
          </indexConfigurations>
        </contentSearch>
      </sitecore>
    </configuration>
  3. Rebuild the search indexes.
  4. Apply the following ordering LINQ conditions:
    .OrderBy(item => item.Order).ThenBy(item => item.Name);
    
    
    Where Order is a property on a custom type derived from SearchResultItem, e.g.
    
    
    public class CustomSearchResultItem : Sitecore.ContentSearch.SearchTypes.SearchResultItem
    {
      [Sitecore.ContentSearch.IndexField("sortOrder")]
      public int Order { get; set; }
    
    }