【问题标题】:Sunspot / Solr / Rails: Model Associations are not updating in the IndexSunspot / Solr / Rails:模型关联未在索引中更新
【发布时间】:2011-11-15 15:14:47
【问题描述】:

我的应用程序中有一个 Fieldnote 模型,它通过一个名为 :fieldnote_activities 的表附加了多个 :activities。然后我以这种方式定义一个可搜索的索引:

searchable :auto_index => true, :auto_remove => true do
  integer :id
  integer :user_id, :references => User

  integer :activity_ids, :multiple => true do
    activities.map(&:id)
  end

  text :observations
 end

然后我有一个搜索模型来存储/更新搜索。因此,搜索模型也与活动有自己的关联。然后我像这样执行我的搜索:

@search = Search.find(params[:id])
@query  = Fieldnote.search do |query|
  query.keywords  @search.terms

  if @search.activities.map(&:id).empty? == false
    query.with    :activity_ids, @search.activities.map(&:id)
  end

end
@fieldnotes = @query.results

现在这一切都很好。问题是,如果我更改与 fieldnote 关联的活动,搜索结果不会更改,因为该 fieldnote 的索引似乎不会更改。当我定义可搜索索引时,我的印象是 :auto_index => true 和 :auto_remove => true 标志会跟踪新的关联(或删除的关联),但情况似乎并非如此。我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails-3 solr sunspot


    【解决方案1】:

    您说得对,:auto_index:auto_remove 不适用于关联对象,仅适用于指定它们的 searchable 对象。

    反规范化时,您应该在关联对象上使用after_save 挂钩,以便在必要时触发重新索引。在这种情况下,您希望更改 Activity 模型 FieldnoteActivity 连接模型以在保存或销毁时触发其关联的 Fieldnote 对象的重新索引。

    class Fieldnote
      has_many :fieldnote_activities
      has_many :activities, :through => :fieldnote_activities
    
      searchable do
        # index denormalized data from activities
      end
    end
    
    class FieldnoteActivity
      has_many :fieldnotes
      has_many :activities
    
      after_save :reindex_fieldnotes
      before_destroy :reindex_fieldnotes
    
      def reindex_fieldnotes
        Sunspot.index(fieldnotes)
      end
    end
    
    class Activity
      has_many :fieldnote_activities
      has_many :fieldnotes, :through => :fieldnote_activities
    
      after_save :reindex_fieldnotes
      before_destroy :reindex_fieldnotes
    
      def reindex_fieldnotes
        Sunspot.index(fieldnotes)
      end
    end
    

    【讨论】:

    • 非常感谢。我实际上最终使用了after_destroy(否则它会在关联仍然完好无损的情况下重新索引),而不是做 Sunspot.index(fieldnotes) 我在 FieldnoteActivity 模型中编写了一个私有方法,它只是做了fieldnote.index! (即,重新索引一个字段注释而不是全部)。感谢您让我走上正确的道路!
    • 正确的方法是进行around_destroy 回调,因为在before_destroy 中重新索引将不起作用,因为活动尚未被删除。在 after_save 中,关联将为空,因此不会重新索引活动!所以在 around_destroy 中,抓取活动然后让出,然后重新索引这些活动。
    • 如果我有一个多态,请问如何重新索引?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多