前提
- Gemfile
ruby '2.2.2'
〜略〜
source 'https://rubygems.org' do
〜略〜
gem 'elasticsearch-model', '0.1.7'
gem 'elasticsearch-rails', '0.1.7'
gem 'elasticsearch-extensions', '0.0.18'
end
作成したアプリにおけるindexについて
-
elasticsearch-model
のindex_document
,update_document
,delete_document
を利用する方針にした - 一つの
index
に対して複数のテーブルから情報をmerge
して投入するため、as_indexed_json
を編集した- 以下イメージ
def as_indexed_json(_options = {})
{ id: id,
name: name,
address: address,
service_name: service.name,
detail: section.title,
}
end
この状況に置ける問題点
-
section.title
だけに更新が走った時にupdate_document
でデータがうまく更新されない
調査した結果
- elasticsearch-model-0.1.7/lib/elasticsearch/model/indexing.rb
-
changed_attributes
の辺りで基本となるテーブルに対する更新がないとupdate
されないようになってるっぽい
-
def update_document(options={})
if changed_attributes = self.instance_variable_get(:@__changed_attributes)
attributes = if respond_to?(:as_indexed_json)
self.as_indexed_json.select { |k,v| changed_attributes.keys.map(&:to_s).include? k.to_s }
else
changed_attributes
end
client.update(
{ index: index_name,
type: document_type,
id: self.id,
body: { doc: attributes } }.merge(options)
)
else
index_document(options)
end
end
対策
- 消して作りなおす!
- ダウンタイムは一旦無視する!!!
after_commit :update_elasticsearch
def update_elasticsearch
begin
__elasticsearch__.delete_document
rescue StandardError => e
end
begin
__elasticsearch__.index_document
rescue StandardError => e
Rails.logger.error e.message
end
end