base_importer.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # frozen_string_literal: true
  2. class Importer::BaseImporter
  3. # @param [Integer] batch_size
  4. # @param [Concurrent::ThreadPoolExecutor] executor
  5. def initialize(batch_size:, executor:)
  6. @batch_size = batch_size
  7. @executor = executor
  8. @wait_for = Concurrent::Set.new
  9. end
  10. # Callback to run when a concurrent work unit completes
  11. # @param [Proc]
  12. def on_progress(&block)
  13. @on_progress = block
  14. end
  15. # Callback to run when a concurrent work unit fails
  16. # @param [Proc]
  17. def on_failure(&block)
  18. @on_failure = block
  19. end
  20. # Reduce resource usage during and improve speed of indexing
  21. def optimize_for_import!
  22. Chewy.client.indices.put_settings index: index.index_name, body: { index: { refresh_interval: -1 } }
  23. end
  24. # Restore original index settings
  25. def optimize_for_search!
  26. Chewy.client.indices.put_settings index: index.index_name, body: { index: { refresh_interval: index.settings_hash[:settings][:index][:refresh_interval] } }
  27. end
  28. # Estimate the amount of documents that would be indexed. Not exact!
  29. # @returns [Integer]
  30. def estimate!
  31. ActiveRecord::Base.connection_pool.with_connection { |connection| connection.select_one("SELECT reltuples AS estimate FROM pg_class WHERE relname = '#{index.adapter.target.table_name}'")['estimate'].to_i }
  32. end
  33. # Import data from the database into the index
  34. def import!
  35. raise NotImplementedError
  36. end
  37. # Remove documents from the index that no longer exist in the database
  38. def clean_up!
  39. index.scroll_batches do |documents|
  40. ids = documents.map { |doc| doc['_id'] }
  41. existence_map = index.adapter.target.where(id: ids).pluck(:id).each_with_object({}) { |id, map| map[id.to_s] = true }
  42. tmp = ids.reject { |id| existence_map[id] }
  43. next if tmp.empty?
  44. in_work_unit(tmp) do |deleted_ids|
  45. bulk = Chewy::Index::Import::BulkBuilder.new(index, delete: deleted_ids).bulk_body
  46. Chewy::Index::Import::BulkRequest.new(index).perform(bulk)
  47. [0, bulk.size]
  48. end
  49. end
  50. wait!
  51. end
  52. protected
  53. def in_work_unit(*args, &block)
  54. work_unit = Concurrent::Promises.future_on(@executor, *args, &block)
  55. work_unit.on_fulfillment!(&@on_progress)
  56. work_unit.on_rejection!(&@on_failure)
  57. work_unit.on_resolution! { @wait_for.delete(work_unit) }
  58. @wait_for << work_unit
  59. rescue Concurrent::RejectedExecutionError
  60. sleep(0.1) && retry # Backpressure
  61. end
  62. def wait!
  63. Concurrent::Promises.zip(*@wait_for).wait
  64. end
  65. def index
  66. raise NotImplementedError
  67. end
  68. end