Get summary information for Sunspot search paginated collection

199 views Asked by At

I have looked around a bit and I can't seem to find anything on the best way to do this. Basically, I have sunspot search that I am using to search across multiple model types. The search works fine and looks something like this:

@search = Sunspot.search(Blogpost,Employee) do fulltext 'showcase OR dan' end

It returns multiple object from different models, for example:

 @search.hits           
 => [#<Sunspot::Search::Hit:Employee 645114968>, #<Sunspot::Search::Hit:Blogpost 980190967>, #<Sunspot::Search::Hit:Blogpost 980190970>]

The search hits are of type: Sunspot::Search::PaginatedCollection

What I'd like to be able to do is provide summary count information for this data, for example, "there are two blogposts and one employee". Is there any way to sum the counts of each object type in this collection? I appreciate you taking the time to help me.

2

There are 2 answers

3
Milind On
    @search = Sunspot.search(Blogpost,Employee) do fulltext 'showcase OR dan' end
    ###group by class
    ###edited answer using results##########
    @[email protected]_by(&:class)
    ##get individual models
    @blogs=@search_items[Blog]
    ##get the count
    @blogs_count=@search_items[Blog].count
    @employees_count=@search_items[Employee].count
    ##to sum up the counts of all models
    @total_count=@blogs_count+@employees_count

..HOPE IT HELPS

0
a2f0 On

This seems to work. Thank you for your help milind.

2.0.0-p576 :167 > @search = Sunspot.search(Blogpost,Employee) do fulltext 'showcase OR dan or showcase2' end
D, [2014-11-18T07:10:55.188290 #8012] DEBUG -- :   SOLR Request (3.9ms)  [ path=select parameters={fq: ["type:(Blogpost OR Employee)"], q: "showcase OR dan or showcase2", fl: "* score", qf: "title_text firstName_text lastName_text", defType: "edismax", start: 0, rows: 30} ]
 => <Sunspot::Search:{:fq=>["type:(Blogpost OR Employee)"], :q=>"showcase OR dan or showcase2", :fl=>"* score", :qf=>"title_text firstName_text lastName_text", :defType=>"edismax", :start=>0, :rows=>30}> 
2.0.0-p576 :168 > @map = @search.hits.map{|a| a.class_name}
=> ["Employee", "Blogpost", "Blogpost"] 
2.0.0-p576 :169 > @map.inject(Hash.new(0)) {|h,x| h[x]+=1;h}
=> {"Employee"=>1, "Blogpost"=>2} 
2.0.0-p576 :170 >