Skip to content

Instantly share code, notes, and snippets.

@mreinsch
Last active October 8, 2015 06:41
Show Gist options
  • Save mreinsch/acb2f6c58891e5cd4f13 to your computer and use it in GitHub Desktop.
Save mreinsch/acb2f6c58891e5cd4f13 to your computer and use it in GitHub Desktop.
example on how we're handling object dependencies when objects in elasticsearch need update. In our case, the JSON for an event includes data from the group, so whenever the group changes, the event needs to be updated as well. Also, if a group is closed, we want to remove it and all events from the index.
class Event < ActiveRecord::Base
include Elasticsearch::Model
belongs_to :group
after_save { IndexerJob.perform_later('update', self.class.name, self.id) }
after_destroy { IndexerJob.perform_later('delete', self.class.name, self.id) }
def in_search_index?
published? && group.in_search_index?
end
def update_related_objects_in_index
end
end
class Group < ActiveRecord::Base
include Elasticsearch::Model
has_many :events
after_save { IndexerJob.perform_later('update', self.class.name, self.id) }
after_destroy { IndexerJob.perform_later('delete', self.class.name, self.id) }
def in_search_index?
!private? && !closed?
end
def update_related_objects_in_index
events.each {|e| IndexerJob.perform_later('update', e.class.name, e.id) }
end
end
class IndexerJob < ActiveJob::Base
queue_as :default
def perform(action, record_type, record_id)
logger.info "#{action} on #{record_type} ID #{record_id}"
record_class = record_type.constantize
record_data = { index: record_class.index_name, type: record_class.document_type, id: record_id }
client = record_class.__elasticsearch__.client
case action.to_s
when 'update'
record = record_class.find_by_id(record_id)
if record && record.in_search_index?
client.index record_data.merge(body: record.as_indexed_json)
else
client.delete record_data.merge(ignore: 404)
end
record.update_related_objects_in_index if record
when 'delete'
client.delete record_data.merge(ignore: 404)
else
raise ArgumentError, "Unknown action '#{action}'"
end
end
rescue_from(RuntimeError) do |exception|
raise exception if Rails.env.test?
if defined? Raven
Raven.capture_exception(exception, extra: { :job => self })
else
raise exception
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment