如何使用Elasticsearch gem和delayed_job索引ActiveRecord模型异步

时间:2016-01-12 01:43:30

标签: activerecord elasticsearch delayed-job

如何使用elasticsearch索引async,类似于sidekiq example

我使用的是delayed_job而不是sidekiq。

1 个答案:

答案 0 :(得分:3)

创建一个可搜索的关注点和一个特殊的索引器类(我把它放在lib / indexer.rb中),它可以与任何ActiveRecord模型一起使用,并按ID查找。

<强>顾虑/ searchable.rb

require 'elasticsearch/model'

module searchable
  extend activesupport::concern

  included do
    include elasticsearch::model
    after_touch() {indexer.delay.update(self.class.name, id)}

    after_commit lambda {indexer.delay.create(self.class.name, id)},  on: :create
    after_commit lambda {indexer.delay.update(self.class.name, id)},  on: :update
    after_destroy lambda {indexer.delay.delete(self.class.name, id)}
  end

end

<强> LIB / indexer.rb

class Indexer
  def self.create(klass_name, id)
    doc = klass_name.constantize.find(id)
    doc.__elasticsearch__.index_document
  end

  def self.update(klass_name, id)
    doc = klass_name.constantize.find(id)
    doc.__elasticsearch__.update_document
  end

  def self.delete(klass_name, id)
    # it's already deleted, so we have to delete it old school
    doc = klass_name.constantize.new
    doc.id = id
    doc.__elasticsearch__.delete_document 
  end

end