Sitecore 8.2 Lucene Search: An Issue with Sorting by Number Field with Decimals

Sitecore 8.2 Lucene Search: Sorting by Number field with decimals issue.

The Problem

In one of our Siteore projects we've bumped into the issue:

By default, In the Sitecore Lucene mappings, filed type “number” got mapping to the System.Double type:

      

<fieldType type="System.Double" fieldTypeName="number" storageType="NO" indexType="TOKENIZED" vectorType="NO" boost="1f" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider"/>

 

But Lucene sorting (lucene.net) provides following sorting valid types for sorting (https://lucenenet.apache.org/docs/3.0.3/d1/da9/class_lucene_1_1_net_1_1_search_1_1_sort.html):

There are four possible kinds of term values which may be put into sorting fields: Integers, Longs, Floats, or Strings.

Here's the problem: by default, “Number” field got mapping to the double, but sorting by double is not allowed in the Lucene 3.0.3 (but in the reality, we still can sort by this filed).

This leads us to the following issue when we are sorting by “Number” in the Sitecore Lucene search:
The field type “number” with decimals in the values are sorted incorrect in Sitecore Lucene search.

The Solution:

To follow Lucene.net documentation: we need to have float instead of double for sorting number field (according to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/built-in-types-table - this is a System.Single).

Let's say we have a Number “price” field for sorting, so we need to keep this field in the index as System.Single instead of default System.Double:

      
<field type="System.Single" fieldName="price" storageType="YES" indexType="TOKENIZED" vectorType="NO" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
<Analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider"/>
</field>
 

And, in our index model we should describe this field as float, similar to this:

      
[IndexField("price")]
[TypeConverter(typeof(IndexFieldFloatingPointNumberValueConverter))]
public virtual float Price { get; set; }
 

Now, Lucene search sorting (OrderBy) for this field will be working correct for Sitecore field type number with decimals in the value.

Questions or comments? Drop us a line here and share what you think.