statuses_index_importer.rb 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # frozen_string_literal: true
  2. class Importer::StatusesIndexImporter < Importer::BaseImporter
  3. def import!
  4. # The idea is that instead of iterating over all statuses in the database
  5. # and calculating the searchable_by for each of them (majority of which
  6. # would be empty), we approach the index from the other end
  7. scopes.each do |scope|
  8. # We could be tempted to keep track of status IDs we have already processed
  9. # from a different scope to avoid indexing them multiple times, but that
  10. # could end up being a very large array
  11. scope.find_in_batches(batch_size: @batch_size) do |tmp|
  12. in_work_unit(tmp.map(&:status_id)) do |status_ids|
  13. bulk = ActiveRecord::Base.connection_pool.with_connection do
  14. Chewy::Index::Import::BulkBuilder.new(index, to_index: Status.includes(:media_attachments, :preloadable_poll).where(id: status_ids)).bulk_body
  15. end
  16. indexed = 0
  17. deleted = 0
  18. # We can't use the delete_if proc to do the filtering because delete_if
  19. # is called before rendering the data and we need to filter based
  20. # on the results of the filter, so this filtering happens here instead
  21. bulk.map! do |entry|
  22. new_entry = begin
  23. if entry[:index] && entry.dig(:index, :data, 'searchable_by').blank?
  24. { delete: entry[:index].except(:data) }
  25. else
  26. entry
  27. end
  28. end
  29. if new_entry[:index]
  30. indexed += 1
  31. else
  32. deleted += 1
  33. end
  34. new_entry
  35. end
  36. Chewy::Index::Import::BulkRequest.new(index).perform(bulk)
  37. [indexed, deleted]
  38. end
  39. end
  40. end
  41. wait!
  42. end
  43. private
  44. def index
  45. StatusesIndex
  46. end
  47. def scopes
  48. [
  49. local_statuses_scope,
  50. local_mentions_scope,
  51. local_favourites_scope,
  52. local_votes_scope,
  53. local_bookmarks_scope,
  54. ]
  55. end
  56. def local_mentions_scope
  57. Mention.where(account: Account.local, silent: false).select(:id, :status_id)
  58. end
  59. def local_favourites_scope
  60. Favourite.where(account: Account.local).select(:id, :status_id)
  61. end
  62. def local_bookmarks_scope
  63. Bookmark.select(:id, :status_id)
  64. end
  65. def local_votes_scope
  66. Poll.joins(:votes).where(votes: { account: Account.local }).select('polls.id, polls.status_id')
  67. end
  68. def local_statuses_scope
  69. Status.local.select('"statuses"."id", COALESCE("statuses"."reblog_of_id", "statuses"."id") AS status_id')
  70. end
  71. end