在Thinking Sphinx中使用Delta Indexes进行关联

时间:2011-02-04 20:50:40

标签: ruby-on-rails ruby thinking-sphinx

我有一个产品型号:

class Product < ActiveRecord::Base
    belongs_to :subcategory

    define_index do

        # fields
        indexes subcategory.name, :as => :subcategory, :sortable => true, :facet => true

        # attributes
        has subcategory_id, created_at, updated_at

        #properties
        set_property :delta => true

现在,假设用户更新子类别名称,这是更新产品增量索引的正确方法吗?

根据该文档:http://freelancing-god.github.com/ts/en/deltas.html,一个保存消息应当被发送到的产物,所以在这种情况下,我应去用于与子类别相关的每个产品,并发送保存消息,如下所示:

class Subcategory < ActiveRecord::Base
    has_many :products

    after_save :set_product_delta_flag

    private

    def set_product_delta_flag
        products.each { |product|
        product.delta = true
        product.save
     }
    end
  end

我认为这是过度的,因为我们每个子类别都有100.000个产品。 这是更新delta指数的正确方法吗?我错过了什么吗?

添加后:

def set_product_delta_flag
    Product.update_all ['delta = ?', true], ['subcategory_id = ?', id]
    Product.index_delta
end

我总是收到这个错误:

NoMethodError(#的未定义方法`index_delta'):

因此,此问题的解决方案是将消息* define_indexes *发送到Product模型。

修复此问题后,一切正常,但delta_index未正确更新,我需要保存两次到子类别模型。

所以我的最终解决方案就是这个:

after_commit :set_product_delta_flag

private

def set_product_delta_flag
    Product.define_indexes
    Product.update_all ['delta = ?', true], ['subcategory_id = ?', id]
    Product.index_delta
end

使用 after_commit define_indexes 是正确的解决方案吗?它是我发现的唯一一个。

1 个答案:

答案 0 :(得分:4)

请尝试以下方法:

def set_product_delta_flag
  Product.update_all ['delta = ?', true], ['subcategory_id = ?', id]
  Product.index_delta
end

单个SQL语句,单个delta重新索引。应该表现得更好:))