Class: Searchkick::ProcessBatchJob

Inherits:
ActiveJob::Base
  • Object
show all
Defined in:
lib/searchkick/process_batch_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(class_name:, record_ids:, index_name: nil) ⇒ Object


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/searchkick/process_batch_job.rb', line 5

def perform(class_name:, record_ids:, index_name: nil)
  # separate routing from id
  routing = Hash[record_ids.map { |r| r.split(/(?<!\|)\|(?!\|)/, 2).map { |v| v.gsub("||", "|") } }]
  record_ids = routing.keys

  klass = class_name.constantize
  scope = Searchkick.load_records(klass, record_ids)
  scope = scope.search_import if scope.respond_to?(:search_import)
  records = scope.select(&:should_index?)

  # determine which records to delete
  delete_ids = record_ids - records.map { |r| r.id.to_s }
  delete_records = delete_ids.map do |id|
    m = klass.new
    m.id = id
    if routing[id]
      m.define_singleton_method(:search_routing) do
        routing[id]
      end
    end
    m
  end

  # bulk reindex
  index = klass.searchkick_index(name: index_name)
  Searchkick.callbacks(:bulk) do
    index.bulk_index(records) if records.any?
    index.bulk_delete(delete_records) if delete_records.any?
  end
end