Commit ae5a7e943f80facb7253ab346080c2dc6df0b4b0

Authored by Andrew Kane
1 parent 2257e54e

Refactored reindex method

lib/searchkick/index.rb
... ... @@ -22,6 +22,21 @@ module Searchkick
22 22 client.indices.refresh index: name
23 23 end
24 24  
  25 + def alias_exists?
  26 + client.indices.exists_alias name: name
  27 + end
  28 +
  29 + def swap(new_name)
  30 + old_indices =
  31 + begin
  32 + client.indices.get_alias(name: name).keys
  33 + rescue Elasticsearch::Transport::Transport::Errors::NotFound
  34 + []
  35 + end
  36 + actions = old_indices.map{|old_name| {remove: {index: old_name, alias: name}} } + [{add: {index: new_name, alias: name}}]
  37 + client.indices.update_aliases body: {actions: actions}
  38 + end
  39 +
25 40 def store(record)
26 41 client.index(
27 42 index: name,
... ...
lib/searchkick/reindex.rb
... ... @@ -6,27 +6,21 @@ module Searchkick
6 6 def reindex(options = {})
7 7 skip_import = options[:import] == false
8 8  
9   - alias_name = searchkick_index.name
10   - new_name = "#{alias_name}_#{Time.now.strftime('%Y%m%d%H%M%S%L')}"
11   - index = Searchkick::Index.new(new_name)
12   -
13 9 clean_indices
14 10  
15   - index.create searchkick_index_options
  11 + index = searchkick_create_index
16 12  
17 13 # check if alias exists
18   - if Searchkick.client.indices.exists_alias(name: alias_name)
  14 + if searchkick_index.alias_exists?
19 15 # import before swap
20 16 searchkick_import(index: index) unless skip_import
21 17  
22 18 # get existing indices to remove
23   - old_indices = Searchkick.client.indices.get_alias(name: alias_name).keys
24   - actions = old_indices.map{|name| {remove: {index: name, alias: alias_name}} } + [{add: {index: new_name, alias: alias_name}}]
25   - Searchkick.client.indices.update_aliases body: {actions: actions}
  19 + searchkick_index.swap(index.name)
26 20 clean_indices
27 21 else
28 22 searchkick_index.delete if searchkick_index.exists?
29   - Searchkick.client.indices.update_aliases body: {actions: [{add: {index: new_name, alias: alias_name}}]}
  23 + searchkick_index.swap(index.name)
30 24  
31 25 # import after swap
32 26 searchkick_import(index: index) unless skip_import
... ... @@ -78,6 +72,12 @@ module Searchkick
78 72 end
79 73 end
80 74  
  75 + def searchkick_create_index
  76 + index = Searchkick::Index.new("#{searchkick_index.name}_#{Time.now.strftime('%Y%m%d%H%M%S%L')}")
  77 + index.create searchkick_index_options
  78 + index
  79 + end
  80 +
81 81 def searchkick_index_options
82 82 options = searchkick_options
83 83  
... ...