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

How to index ActiveRecord models async with Elasticsearch gem and delayed_job

我如何使用 elasticsearch 来索引异步类似于 sidekiq example

我正在使用 delayed_job 而不是 sidekiq。

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

concerns/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