【问题标题】:How can I order Sunspot search results for a query on multiple models?如何为多个型号的查询订购 Sunspot 搜索结果?
【发布时间】:2014-09-27 13:07:10
【问题描述】:

我有两个期刊模型,ClientJournalInstitutionJournal,我正在使用 Sunspot 运行一个查询,该查询会抓取记录以将它们一起显示在期刊索引页面上:

search = Sunspot.search ClientJournal, InstitutionJournal do
  paginate page: params[:page], per_page: 30
  order_by :created_at, :desc
end

这几乎可行,但它在排序之前将结果分成两个类,因此search.results 返回如下内容:

created_at  class
09:30       ClientJournal
09:12       ClientJournal
08:57       ClientJournal
07:32       ClientJournal
09:45       InstitutionJournal
09:22       InstitutionJournal
09:07       InstitutionJournal

我真正想要的是这样的:

created_at  class
09:45       InstitutionJournal
09:30       ClientJournal
09:22       InstitutionJournal
09:12       ClientJournal
09:07       InstitutionJournal
08:57       ClientJournal
07:32       ClientJournal

有没有办法告诉 Sunspot 将结果排序在一起,就好像它们是同一个模型一样?

【问题讨论】:

  • 你有想过这个吗?

标签: ruby-on-rails solr sunspot


【解决方案1】:

您可以这样做来搜索多个模型并首先获取单个模型数组,然后像我一样对它们进行排序:-

search = Sunspot.search ClientJournal,InstitutionJournal  do
           keywords(params[:search])
          #fulltext params[:search]
          order_by(:created_at, :desc)
          paginate :page => params[:page], :per_page => 10
         end 
##group them by class
 @results = search.results.group_by(&:class)
##get all clientjournals in created_at order
@clientjournals= @results[ClientJournal]
##OR do anything that you want with the array of cilentjournals
@clientjournals= @clientjournals.sort_by { |a| a.created_at }

【讨论】:

  • 问题在于,您只对一页返回的 10 个结果进行排序。如果您从搜索块中删除 paginate 以避免这种情况,那么您最终可能会在一个数组中得到数千个结果,这将非常慢。
猜你喜欢
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
  • 2012-01-18
相关资源
最近更新 更多