关于Rails+Elasticsearch中的index_document

前提是一个条件或假定的基础。

    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

关于创建的应用程序中的索引

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
广告
将在 10 秒后关闭
bannerAds