Created
September 17, 2014 04:40
-
-
Save nick-skriabin/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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(Y)