Created
May 18, 2022 00:33
-
-
Save lazaronixon/82b939179f2b1ee01b4111c8f471db83 to your computer and use it in GitHub Desktop.
Elastic search index async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ElasticsearchExtension | |
module Callbacks | |
extend ActiveSupport::Concern | |
included do | |
after_commit -> { IndexJob.perform_later(:create, self.class.name, self.id) }, on: :create | |
after_commit -> { IndexJob.perform_later(:update, self.class.name, self.id) }, on: :update | |
after_commit -> { IndexJob.perform_later(:destroy, self.class.name, self.id) }, on: :destroy | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ElasticsearchExtension::IndexJob < ActiveJob::Base | |
discard_on ActiveRecord::RecordNotFound | |
discard_on Elasticsearch::Transport::Transport::Errors::NotFound | |
def perform(operation, record_class, record_id) | |
case operation | |
when :create | |
record = record_class.constantize.find(record_id) | |
record.__elasticsearch__.index_document | |
when :update | |
record = record_class.constantize.find(record_id) | |
record.__elasticsearch__.update_document | |
when :destroy | |
client = record_class.constantize.__elasticsearch__.client | |
index_name = record_class.constantize.__elasticsearch__.index_name | |
document_type = record_class.constantize.__elasticsearch__.document_type | |
client.delete index: index_name, type: document_type, id: record_id | |
else raise ArgumentError, "Unknown operation '#{operation}'" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment