Skip to content

Instantly share code, notes, and snippets.

@nicholasrq
Created September 17, 2014 04:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicholasrq/25c699ecaa999d250219 to your computer and use it in GitHub Desktop.
Save nicholasrq/25c699ecaa999d250219 to your computer and use it in GitHub Desktop.
Method to reindex sunspot model with progress bar. You just need to add it to any of your models.
def self.reindex!
model_name = self.name.to_s
total = self.count
indexed = 0.to_f
progress = 0.to_f
row_length = 100.to_f
log_level = Sunspot::Rails::LogSubscriber.logger.level
time_start = Time.now
each_second = Time.now
per_second = 0
per_second_out = 0
#Turn logs off
old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
puts "[SOLR] Start indexing #{model_name}"
Sunspot::Rails::LogSubscriber.logger.level = 4
self.find_in_batches(batch_size: 100) do |group|
group.each do |entry|
entry.index
indexed += 1
progress = (indexed.to_f / total.to_f * 100.to_f)
line = '=' * (row_length / 100 * progress).to_i
space = ' ' * (row_length - line.length.to_f).to_i
printf "[SOLR] Indexing #{indexed.to_i}/#{total} [#{line}>#{space}] #{per_second_out}/sec\r"
if (Time.now - each_second) > 1.to_f
each_second = Time.now
per_second_out = per_second
per_second = 0
else
per_second += 1
end
end
end
time_end = Time.now
puts "\n\r[SOLR] Indexing of #{model_name.pluralize} done [#{indexed.to_i} #{model_name.pluralize.downcase}] in #{time_end - time_start}"
Sunspot::Rails::LogSubscriber.logger.level = log_level
ActiveRecord::Base.logger = old_logger
nil
end
@IslamAzab
Copy link

(Y)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment