Search results sorting can be slow or even fail for some fields


Description

The issue occurs if the Field Map does not contain configuration for the field that is used as a sorting criterion.
The log files might contain the following error:
24172 2018:03:09 11:43:05 WARN Results endpoint exception
Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
Source: Sitecore.ContentSearch
   at Sitecore.ContentSearch.Utilities.QueryBuilder.ResolveFieldTypeByName(String fieldName, IProviderSearchContext context)
   at Sitecore.ContentSearch.Utilities.QueryBuilder.ApplySorting[T](IProviderSearchContext context, IQueryable`1 searchResultItems, IEnumerable`1 searchModels)
   at Sitecore.ContentSearch.Utilities.QueryBuilder.CreateQuery[T](IProviderSearchContext context, IEnumerable`1 searchStringModel, Item startLocationItem, IEnumerable`1 additionalContexts)
   at Sitecore.ContentSearch.Utilities.QueryBuilder.CreateQuery[T](IProviderSearchContext context, IEnumerable`1 searchStringModel)
   at Sitecore.XA.Foundation.Search.Services.SearchService.GetQuery(String query, String scope, String language, Coordinates center, String siteName, String& indexName)
   at Sitecore.XA.Feature.Search.Controllers.SearchController.GetResults(String v, String q, String s, String l, String g, String o, Int32 e, Int32 p, String sig, String site)

Solution

To resolve this issue, add the field that you want to use for sorting to the Field Map, for example:

<fieldMap type="Sitecore.ContentSearch.SolrProvider.SolrFieldMap, Sitecore.ContentSearch.SolrProvider">

  <fieldNames hint="raw:AddFieldByFieldName">

    <field fieldName="criterion" returnType="string" />

    ...

  </fieldNames>

  ...

</fieldMap>