Categories
Uncategorized

Gracefully reindex Sunspot Solr without dropping indexes

How to reindex your Sunspot Solr models without dropping the entire index first.

If you’re using the Ruby on Rails Sunspot gem for searching your models, running rake sunspot:solr:reindex will drop your entire index before reindexing the models.

If you want to reindex the models gracefully without dropping the indexes first, you can put this task in lib/tasks/sunspot_tasks.rake:

# lib/tasks/sunspot_tasks.rake

namespace :sunspot do
task :reindex_gracefully => :environment do
Dir.glob(Rails.root.join(‘app/models/**/*.rb’)).each { |path| require path }
sunspot_models = Sunspot.searchable

index_options = { :batch_commit => false }

begin
require ‘progress_bar’
total_documents = sunspot_models.map { | m | m.count }.sum
index_options[:progress_bar] = ProgressBar.new(total_documents)
rescue LoadError => e
$stdout.puts “Skipping progress bar: for progress reporting, add gem ‘progress_bar’ to your Gemfile”
rescue Exception => e
$stderr.puts “Error using progress bar: #{e.message}”
end

sunspot_models.each do |model|
model.solr_index index_options
end
end
end
The task is a simplified, slightly modified version of Sunspot’s built-in sunspot:reindex task.

Then run:

$ rake sunspot:reindex_gracefully
Now you can reindex without dropping the index. Enjoy 🙂