トークン化されたフィールドで検索結果を並べ替える方法


解説

検索結果は、デフォルトで関連性の高い順に並べられます。つまり、検索クエリにマッチする文書ほど、検索結果の上位に表示されます。しかし場合によっては、検索結果を特定のフィールドで並べ替えたい場合があります。本記事では、その方法について解説します。

例1 - アイテムフィールドでソートする:

例として、タイトル フィールドを使用します。タイトルはSitecore XPのデフォルトのフィールドです。Solrの設定では、テキスト フィールドとして定義されています:

<fieldNames hint="raw:AddFieldByFieldName">
  <field fieldName="title" returnType="text" />
</fieldNames>

テキスト フィールドは、Solrの動的なフィールドにマッピングされます:

<typeMatches hint="raw:AddTypeMatch">
    <typeMatch typeName="text" type="System.String" fieldNameFormat="{0}_t" cultureFormat="_{1}"  
     settingType="Sitecore.ContentSearch.SolrProvider.SolrSearchFieldConfiguration, Sitecore.ContentSearch.SolrProvider" />
</typematches>

動的フィールドはSolrスキーマ ファイルで定義され、text_generalフィールド タイプ(またはカルチャ固有の同等のもの)にマッピングされます:

<dynamicField name="*_t" type="text_general" indexed="true" stored="true"/>
<dynamicField name="*_t_en" type="text_general" indexed="true" stored="true"/>
<dynamicField name="*_t_da" type="text_da" indexed="true" stored="true"/>

例2 - 特殊なフィールドでソートする:

特殊なインデックス フィールドは、Sitecore XPのシステム フィールドをベースにしています。通常、フィールド名の最初にアンダースコアが1つまたは2つ付いています。このようなフィールドは、例えば、Solrスキーマで直接定義されます:

<field name="_name" type="text_general" indexed="true" stored="true"/>

課題

どちらの場合も、フィールド タイプ定義にはdocValuesが含まれず、StandardTokenizerFactoryが使用されます。 トークナイザーは、入力値を用語(term)に分割します。 StandardTokenizerFactoryは通常、フィールドごとに複数の用語を生成します:

<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100" multiValued="false">
  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
    <filter class="solr.SynonymFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

フィールド コンテンツがトークンとして解析される場合、Solr検索エンジンは一貫したソート順を保証できません:https://lucene.apache.org/solr/guide/6_6/common-query-parameters.html#CommonQueryParameters-ThesortParameter

解決策

オプション1 - 計算されたインデックスフィールド:

  1. 並べ替えに使用されるフィールドの値を返すカスタム計算インデックス フィールドを作成します。
  2. 検索インデックスの構成を更新して、計算されたインデックス フィールドを含めます。 戻り値の型は必ずstringにしてください。
  3. <fields hint="raw:AddComputedIndexField">
      <field fieldName="name" returnType="string">Custom.Assembly.ComputedFields.Name,
    Custom.Assembly</field> </fields>
  4. 検索インデックスを再構築します。

オプション2 - Solrコピー フィールド:

  1. 並べ替えに使用するフィールドを追加します。
    例:
    <field name="name" type="lowercase" indexed="true" stored="false"/>
  2. Solrスキーマを変更して、コピー フィールドを含めます。
    例:
    <copyField source="_name" dest="name" />
  3. 変更したスキーマを有効にするためにSolrコアを再読み込みします。
  4. Sitecore XPを再起動し、Solrからスキーマを再読み込みします。
  5. 検索インデックスを再構築します。