获取Sunspot搜索分页集合的摘要信息

时间:2014-11-18 12:13:28

标签: ruby-on-rails sunspot

我已经环顾四周,似乎无法找到最好的方法来做到这一点。基本上,我有太阳黑子搜索,我用来搜索多个模型类型。搜索工作正常,看起来像这样:

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

它返回来自不同模型的多个对象,例如:

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

搜索命中的类型为:Sunspot :: Search :: PaginatedCollection

我希望能够提供此数据的摘要计数信息,例如“有两个博客帖子和一个员工”。有没有办法对这个集合中每个对象类型的数量求和?感谢您抽出宝贵时间帮助我。

2 个答案:

答案 0 :(得分:0)

    @search = Sunspot.search(Blogpost,Employee) do fulltext 'showcase OR dan' end
    ###group by class
    ###edited answer using results##########
    @search_items=@search.results.flatten.compact.group_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

..希望它能帮助

答案 1 :(得分:0)

这似乎有效。谢谢你的帮助。

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 >