2010-08-02 33 views
1

我使用Thinking Sphinx来为我的Rails应用程序搜索。在Sphinx搜索中包含Rails ActiveRecord方法

我知道指南明确说you can't index model methods,但我想。具体来说,我有一个模型,其实例可以通过has_many_through关系通过acts_as_taggable_on_steroids进行标记。重要的警告:模型也嵌套通过awesome_nested_set,并且我有通过嵌套继承的标签。

这里是我如何寻找继承标签:

def inherited_tags 
    retval = [] 
    cat = self 
    while (cat = cat.parent) 
    retval += cat.tags 
    end 
    retval.uniq 
end 

我能够通过显式(非继承)搜索标签使用:

define_index do 
    indexes title 
    indexes tags(:name) 
end 

此搜索似乎工作就好了,但我无法将它们结合起来以允许用户使用继承标签进行搜索。任何意见非常感谢!

+0

如果你的问题是不相关的狮身人面像,搜索引擎,你可以请删除狮身人面像标签? – 2010-08-02 19:33:22

+0

这是一个狮身人面像问题 - 思考狮身人面像是一个轨道插件与狮身人面像整合 – 2010-08-03 00:03:55

回答

2

狮身人面像只能索引数据库中的数据,这是没有办法的(有一个XML选项,但思维狮身人面像不支持它)。

最好的办法是向您的模型添加一个缓存的属性,这对用户是不可见的,但用于搜索。

试着这么做:

class Category < ActiveRecord::Base 
    define_index do 
    indexes title 
    indexes cached_tags, :as => :tags 
    end 

    before_validate :cache_tags  

    def ancestors 
    if self.parent 
     self.parent.ancestors + [self.parent] 
    else 
     [] 
    end 
    end 

    def inherited_tags 
    ancestors.map { |cat| cat.tags }.flatten.uniq 
    end 

    private 

    def cache_tags 
    self.cached_tags ||= inherited_tags.join(" ") 
    end  
end 
+0

我同意这种评估情况,詹姆斯。出于性能考虑,实际的解决方案必然会稍微复杂一些(例如,在您的解决方案中,在根类别中添加标签不会为祖先更新缓存标签,并且引入这种冒泡会导致根类别的编辑标签相当慢)。我可能要么编辑更新思维狮身人面像索引以计算整个板上缓存标签的rake任务,要么我会放入一些本机SQL字符串操作来加速它。感谢您的工作! – 2010-08-03 13:12:54