Skip to content

Instantly share code, notes, and snippets.

@woahdae
Created January 18, 2012 17:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woahdae/1634344 to your computer and use it in GitHub Desktop.
Save woahdae/1634344 to your computer and use it in GitHub Desktop.
On-the-fly index rotation
module Tire
def self.inverted_aliases
aliases.inject({}) do |acc, (index, aliases)|
aliases.each do |als|
acc[als] ||= SortedSet.new
acc[als] << index
end
acc
end
end
def self.reindex(klass, options = {})
scope = options[:scope] || klass.scoped
index_alias = klass.index_name
# Alias-based reindexing when already having a real index is an error state
if Tire.index(index_alias).exists? && !Tire.inverted_aliases[index_alias]
raise "#{klass.index_name} exists and is not an alias"
end
# First, populate the new index
new_index_name = Time.now.strftime("%Y%m%d_%H%M%S")
new_index = Tire.index(new_index_name)
new_index.create(:mappings => klass.mapping_to_hash,
:settings => klass.settings)
scope.find_in_batches do |batch|
new_index.import batch
end
# Create an alias to the new index, so Klass.index points to both
# (elasticsearch supports one alias to many indexes)
new_index.add_alias(index_alias)
# Delete old index
old_index_name = Tire.inverted_aliases[index_alias].first
unless old_index_name == new_index_name
old_index = Tire.index(old_index_name)
old_index.remove_alias(index_alias)
old_index.delete
end
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment