[英]Combining the results of multiple Thinking Sphinx queries into a single paginated result
有沒有一種簡單的方法可以將多個Think Sphinx搜索的結果合並為一個結果? 所有這些搜索都在同一模型上,但是搜索具有不同的搜索詞。 我想做的是合並結果,以便可以按日期列對它們全部排序並獲得適當的分頁。
說我有一個思想家班和一個思想班。
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
...並以某種方式將它們組合在一起,以便將鮑勃(煎餅)和愛麗絲(華夫餅干)的思想集合混合在一起,按created_at降序排序,並按Think Sphinx進行適當分頁。 在實際的用例中,我可以通過這種方式組合進行2到15次搜索。
我知道搜索方法返回ThinkingSphinx :: Search <數組。 我曾考慮過將這些對象手動拼接在一起,但事實上,我正在尋找排序和分頁功能,這一點有些棘手。
在“思想獅身人面像”中是否有一種優雅的方法可以做到這一點,還是我什么都不丟失,而我幾乎必須自己動手做?
認為Sphinx與Kaminari一起工作。 因此,您的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)
您可以對結果使用分頁和簡單排序
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)
希望這可以幫助
您可能可以很容易地做到這一點,但是您需要重寫查詢以使其更通用,並在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.