2012-01-19 105 views
5

是否有一种简单的方法将多个Thinking Sphinx搜索的结果合并为一个结果?所有这些搜索都使用相同的模型,但搜索具有不同的搜索术语。我想要做的是将结果合并,以便它们都可以按日期列排序并获得适当的分页。将多个Thinking Sphinx查询的结果合并为一个分页结果

假设我有一个Thinker类和一个Idea类。

class Thinker < ActiveRecord::Base 
    has_many :ideas 
end 

class Idea < ActiveRecord::Base 
    belongs_to :thinker 

    define_index do 
    indexes text 
    has created_at 
    end 
end 

并说我有两个思想家,鲍勃和爱丽丝。我想下面的搜索结合起来:

bob.ideas.search 'pancakes', :order => :created_at, :sort_mode => :desc 
alice.ideas.search 'waffles', :order => :created_at, :sort_mode => :desc 

...并以某种方式将它们组合起来,这样的Bob的(煎饼)和Alice的(松饼)概念的综合体混合在一起,通过降created_at排序,并适当通过分页思维狮身人面像。在实际使用情况下,我可以在2至15个搜索范围内以这种方式进行组合。

我知道搜索方法返回一个ThinkingSphinx :: Search <数组。我想到了将这些对象手动拼接在一起,但是我正在寻找排序和分页的事实,这使得这有点棘手。

在思考狮身人面像中有没有一种优雅的方式来做到这一点,或者我不会错过任何东西,我几乎必须推出自己的?

回答

0

您可以很容易地做到这一点,但您需要重写您的查询更通用,并搜索Idea模型本身。

Idea.search 'pancakes | waffles', :with => {:thinker_id => [bob.id, alice.id]}, 
            :order => :created_at, 
            :sort_mode => :desc, 
            :match_mode => :boolean 

和你的模型应该是:

class Idea < ActiveRecord::Base 
    belongs_to :thinker 

    define_index do 
    indexes text 
    has created_at, thinker_id 
    end 
end 
+1

伟大的建议,但此查询会发现还发现由Bob包含“薄煎饼”理念包含“华夫饼干”和想法爱丽丝。 我只希望“煎饼”搜索词适用于鲍勃的想法和“华夫饼”爱丽丝的想法。 –

1
first_search = bob.ideas.search 'pancakes', :order => :created_at, :sort_mode => :desc 
second_search = bob.ideas.search 'pancakes', :order => :created_at, :sort_mode => :desc 
results = first_search.flatten + second_search.flatten 

,你现在可以按日期排序像你想

sorted_results = results.sort_by(&:date) 

希望这有助于

4

思考狮身人面像一起工作雷。 所以你已经有你的gemfile kaminari。您只需要:

result = bob.ideas.search 'pancakes', :order => :created_at, :sort_mode => :desc 
result += alice.ideas.search 'waffles', :order => :created_at, :sort_mode => :desc 

结果不再是ThinkingSphinx :: Search。这是一个数组

result = Kaminari.paginate_array(result) 

你可以使用分页和简单排序在结果上

相关问题