LoginSignup
3
3

More than 5 years have passed since last update.

Rails+Elasticsearchにおけるindex_documentについて

Posted at

前提

  • 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-modelindex_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
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3