-
Notifications
You must be signed in to change notification settings - Fork 0
Ordering and pagination
Sunspot allows ordering on one or more non-text fields using the order_by
method in the search DSL (if no order_by
call is made, results are sorted by relevancy). order_by
may be called more than once, and the earlier calls will have higher ordering precedence than the later calls. Each call to the method should take the field name and either :asc
or :desc
:
Sunspot.search(Post) do
order_by(:blog_id, :asc)
order_by(:created_at, :desc)
end
Note that ordering cannot be done on text fields, and if ordering is needed on a text field, then a separate string field can be defined on the same content.
Sunspot also provides two special arguments for the order_by
method. If :random
is passed to order_by
, Solr’s RandomSortField will be used to (usually) return results in a different order each time. If :score
is passed to order_by
, results will be sorted by relevancy, which can be useful if order_by
is called multiple times in order to secondary ordering methods in case of ties in the relevancy score.
In Solr, all searches are paginated . Sunspot sets a default of 30 results per page, although this can be changed globally (see below). To specify pagination explicitly, use the paginate
method, which takes two options: :page
and :per_page
(this should be familiar to anyone who has used WillPaginate). :page
is required.
Sunspot.search(Post) do
paginate(:page => 2, :per_page => 15)
end
You can use :page from the params, for eg:
Sunspot.search(Post) do paginate(:page => params[:page] || 1, :per_page => 2) end
The default number of results to return per page (if no pagination is specified for a particular search) can be changed using the configuration API:
Sunspot.config.pagination.default_per_page = 30