Skip to content

Sorting results

Shannon Deminick edited this page Aug 10, 2016 · 3 revisions

When performing searches with Examine you can also have Examine order the results on a particular field. When the sorting is done by Examine (i.e. Lucene) the processing will be much more efficient than sorting the results after the search results are returned. Further more by having the sorting performed by Lucene, effective paging can be achieved.

By default, the results are sorted by Score which is generally what you'd want. However in some cases you might want to sort on a custom field. This is easily done by using the OrderBy or OrderByDescending methods on the ISearchCriteria instance. For example:

var sc = ExamineManager.Instance.CreateSearchCriteria();

var query = sc.Field("myField", "myValue")

IEnumerable<SearchResult> results = ExamineManager.Instance.Search(     
     query.Compile(), /* prepares the query to be handled by the searcher /*
     100              /* optional max record count */); 

Field types

In many cases you might need to tell Examine what type of data is stored in the field you are sorting on so it knows how to order the results. For example, if the field stores integers then sorting by string is going to return misleading results.

Examine will be try to sort the values that are stored based on strings by default but if the field you have is not a string then the field type should be defined in config along with a flag telling Examine that this field is sortable by it's native format (this affects how it is stored in the index). For example in your index set definition you could have something like this to specify that likes are sortable and have a value type of INT:

<IndexSet SetName="documentationIndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/documentation/">
      <add Name="doc"/>
      <add Name="likes" Type="INT" EnableSorting="true"/>

Then when you are performing a sort operation during searching you use a special syntax to tell Examine that this is a typed field:

var sc = ExamineManager.Instance.CreateSearchCriteria();

var query = sc.Field("doc", "hats")

The different Type values that can be used are (these are Lucene specific):

  • DOC
  • AUTO
  • STRING (default)
  • INT
  • LONG
  • BYTE

It's important to know that if you are sorting by a specific value type then in most cases you should be storing the value as that value type.

You can’t perform that action at this time.