Commit d804f1feb5c2e80297b7942e0506ba8cab9dfc21

Authored by Andrew Kane
1 parent fa1d3df6

Make sure indices are cleaned after a reindex

Showing 2 changed files with 32 additions and 8 deletions   Show diff stats
lib/searchkick/reindex.rb
... ... @@ -17,20 +17,14 @@ module Searchkick
17 17 end
18 18  
19 19 if a = Tire::Alias.find(alias_name)
20   - old_indices = a.indices.dup
21   - old_indices.each do |index|
  20 + a.indices.each do |index|
22 21 a.indices.delete index
23 22 end
24 23  
25 24 a.indices.add new_index
26 25 response = a.save
27 26  
28   - if response.success?
29   - old_indices.each do |index|
30   - i = Tire::Index.new(index)
31   - i.delete
32   - end
33   - end
  27 + clean_indices if response.success?
34 28 else
35 29 tire.index.delete if tire.index.exists?
36 30 response = Tire::Alias.create(name: alias_name, indices: [new_index])
... ... @@ -39,6 +33,16 @@ module Searchkick
39 33 response.success? || (raise response.to_s)
40 34 end
41 35  
  36 + # remove old indices that start w/ index_name
  37 + def clean_indices
  38 + all_indices = JSON.parse(Tire::Configuration.client.get("#{Tire::Configuration.url}/_aliases").body)
  39 + indices = all_indices.select{|k, v| v["aliases"].empty? && k =~ /\A#{Regexp.escape(Product.index_name)}_\d{14}\z/ }.keys
  40 + indices.each do |index_name|
  41 + Tire::Index.new(index_name).delete
  42 + end
  43 + indices
  44 + end
  45 +
42 46 private
43 47  
44 48 def searchkick_index_options
... ...
test/index_test.rb 0 → 100644
... ... @@ -0,0 +1,20 @@
  1 +require_relative "test_helper"
  2 +
  3 +class TestIndex < Minitest::Unit::TestCase
  4 +
  5 + def test_clean_indices
  6 + old_index = Tire::Index.new("products_development_20130801000000")
  7 + different_index = Tire::Index.new("items_development_20130801000000")
  8 +
  9 + # create indexes
  10 + old_index.create
  11 + different_index.create
  12 +
  13 + Product.clean_indices
  14 +
  15 + assert Product.index.exists?
  16 + assert different_index.exists?
  17 + assert !old_index.exists?
  18 + end
  19 +
  20 +end
... ...