rubysortingfacetsunspot

Sunspot: Sort/order facet results by attribute e.g. created_at


Asset model:

searchable do
   text :title
   text :description
   time :created_at
   integer :category_ids, :multiple => true, :references => Category
end

Controller:

search = Asset.search() do
   keywords(h(params[:query]), :fields => [:title, :description])
   facet(:category_ids)
   order_by :created_at
end

I would not like to sort my facet :Category_ides via :count (number of hits). The categories should be ordered by created_at. Looking at the documentation facet(:category_ids, :sort => :count || :index), both options won't work for me.

How can I solve this order problem for facets?


Solution

  • You can just load the facets and then sort them yourself:

    result = Product.solr_search do |s|
      s.keywords params[:q]
      s.facet :category_id
      s.paginate :per_page => 3, :page => @page
    end
    
    facet_rows = result.facet(:category_id).rows.sort { |left,right| left.instance.created_at <=> right.instance.created_at }