検索結果をアイテムの並べ替え順序(SortOrder)でソートする方法


解説

この記事では、アイテムの並べ替え順序SortOrder)で検索結果をソートする推奨方法について記載しています。計算インデックス フィールドを使用すると、コンテンツ ツリー内のアイテムと同じ順序で検索結果を表示するようにソートをカスタマイズすることができます。

アイテムの並べ替え順序による検索結果の順序付けは、すべての検索結果が同じ親アイテムを共有する場合のみ、つまり検索式が以下を含む場合のみ意味をなすことに注意してください:

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

解決策

カスタム計算インデックス フィールドを作成するには、以下を実施します。

  1. IComputedIndexFieldインターフェースを実装するカスタム クラスを作成します。
  2. 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;
    
      }
    
    }
    
  3. 計算インデックス フィールドを設定に追加するには、設定パッチ ファイルを\App_Config\Include\zzz フォルダに作成します。
    <?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>
  4. 検索インデックスを再構築します。
  5. 以下の順序付けLINQ条件を適用します:
    .OrderBy(item => item.Order).ThenBy(item => item.Name);
    
    
    なお、OrderはSearchResultItemから派生したカスタム クラスのプロパティです。 例:
    
    
    public class CustomSearchResultItem : Sitecore.ContentSearch.SearchTypes.SearchResultItem
    {
      [Sitecore.ContentSearch.IndexField("sortOrder")]
      public int Order { get; set; }
    
    }