Sorting Search Results
By default, documents are sorted by relevance and then by
document ID if scores are equal. But what if we want to sort the result
set by the value in one of the fields (e.g., price)? One way to do this is
to retrieve the entire result set and make use of Ruby’s Array#sort method. However, this would take too long for large result sets, not
to mention use up a lot of unnecessary memory. Searcher provides a
:sort parameter for easy sorting. The
easiest way to specify a sort is to pass a sort string. A sort string is a comma-separated list of field
names with an optional DESC modifier to reverse the
sort for that field. The type of the field is automatically detected and
the field sorted accordingly. So Float fields will be
sorted by Float value, and Integer
fields will be sorted by Integer value.
SCORE and DOC_ID can be used in place of field names to sort by relevance and
internal document ID, respectively. Here are some examples:
index.search(query,:sort=>"title, year DESC")index.search(query,:sort=>"SCORE DESC, DOC_ID DESC")index.search(query,:sort=>"SCORE, rating DESC")
Although this will do the job most of the time, you can be a little
more explicit in describing how a result set is sorted by using the Sort
API. You will also need to use the Sort API to take full advantage of sort
caching. There are two classes in the Sort API: Sort and SortField.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access