Sorting

The sorting specification is specified with the sort query parameter. The default is score desc. Here, score is not a field but a special reference to a relevancy number, described in detail in the next chapter. Whereas, desc means descending order; use asc for ascending order. Before Solr 4.2, it needed to be lowercase. In the following example, suppose we search for artists that are not individuals (a previous example in the chapter), and then we might want to ensure that those that are surely bands get top placement ahead of those that are unknown. Secondly, we want the typical descending score search. This would simply be:

sort=a_type desc,score desc

Note

Pay attention to the field types and text analysis you're using in your schema for fields that you sort on. Basically, fields need to be single valued, indexed, and not tokenized. Some, but not all, support sortMissingFirst and sortMissingLast options. See the section on sorting in Chapter 2, Schema Design, for further information.

In addition to sorting on field values and the score, Solr supports sorting on a function query. Function queries are usually mathematical in nature and used for things like computing a geospatial distance or a time difference between now and some field value. Function queries have been discussed in detail in the next chapter, but here's a simple example sorting by the difference between the artist's begin and end date:

sort=sub(a_end_date,a_begin_date) desc

An interesting usecase that has nothing to do with math is a trick to sort based on multivalued field data in limited circumstances. For example, what if we wanted to sort on MusicBrainz releases which are declared to be of type Album (r_type is a multivalued field, remember)? We would use the following:

sort=query({!v="r_type:Album"}) desc

To understand this admittedly complicated expression, read the earlier section on query parsers and local-params, and read the definition of the query() function query in the next chapter. When using the query() function query in a sort expression, you must specify use local-params v parameter to specify the query string, instead of simply using the query string itself because of syntax restrictions in the context of how the sort parameter value is parsed.

Tip

Sorting and memory usage

When you ask Solr to sort on a field, every indexed value is put into an array in memory in Lucene's field cache. Text consumes a lot more memory than numbers. Also, the first time it's needed, it takes a noticeable amount of time to bring in all the values from disk. You should add a query that sorts on the fields your app might sort on into newSearcher in solrconfig.xml.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.190.232