Sort Solr Facets on Per Field Basis

I recently faced a strange problem. I was faceting off of multiple facet.fields and I found the need to sort them independently of each other. As far as I knew up to this point facet.sort could only be set once. When I read the doc, however, it was claimed that the facet.sort could be set on a per field basis; sadly no examples were provided nor was it explained any further. Luckily, after some digging, I found out that setting the sort (index or count) on a per field is very easy.

A typical solr fetch with facets might look like this (assuming type_s is indexed):

/solr/directory/select?q=*:*&wt=json&indent=true&facet=true&facet.field=type_s

Solr sets facet.sort to count by default, so that can be left undeclared or can be explicitly declared, it does not matter. A problem arises, however, when you have multiple facet.fields and you want them sorted differently. To solve this you need to follow this format for the declared sort: f.<facetted_field>.facet.sort=<index|count>. Using the same example as before, but with an extra field it would look like this:

/solr/directory/select?q=*:*&wt=json&indent=true&facet=true&facet.field=type_s&facet.field=location_s&f.location_s.facet.sort=index

This would sort type_s by count (default) and sort location_s by index. The opposite would also work.

/solr/directory/select?q=*:*&wt=json&indent=true&facet=true&facet.field=type_s&facet.field=location_s&facet.sort=index&f.location_s.facet.sort=count

This would change the default sort order to use index for sort and location_s would use count for sorting.

Related Articles