Thinking Sphinx group options
Ok so i have 4 models that I am searching on in one search like this
#category model
define_index do
indexes :name, :description, :tag
indexes sub_categories.name, :as => :subcategory_name
end
#pattern model
define_index do
indexes :name, :tag_name, :reference
indexes colorways.filename, :as => :color_name
end
and so on.... I also have a searches controller that calls them all by this command
@results = ThinkingSphinx.search params[:search], :page => params[:page], :per_开发者_Go百科page => 25
I need to group the results based on the model so for example i want all the graphic results first then the categories and then the subcategories together so in my view i can have all the graphics together and the categories together.....any ideas on the best way to group or sort these by objects...
There's two approaches... firstly, Thinking Sphinx stores a CRC'd version of the class name as an attribute, so you can ask Sphinx to sort by that:
ThinkingSphinx.search params[:search],
:page => params[:page],
:per_page => 25,
:order => 'class_crc ASC, @relevance DESC'
However, this doesn't enforce a specific order (you mentioned you want Graphic results first) - so you may want to consider a different approach - adding a manual attribute to each index definition with an integer determining the order:
has '1', :as => :model_order, :type => :integer
Change the 1 to 2, 3, etc for each index definition depending on where you want it in the search results. And then searching looks like this:
ThinkingSphinx.search params[:search],
:page => params[:page],
:per_page => 25,
:order => 'model_order ASC, @relevance DESC'
Hopefully one of those two options suits what you're after.
A quick and dirty way is to use group_by
and the model class name:
@results.group_by(&:class)
But it probably won't work well for large result sets. For that, you might consider adding the model name as a column in each table, and do the grouping using ThinkingSphinx as described in the docs.
精彩评论