Method: Elasticsearch::Model::Indexing::InstanceMethods#update_document

Defined in:
lib/elasticsearch/model/indexing.rb

#update_document(options = {}) ⇒ Hash

Tries to gather the changed attributes of a model instance (via [ActiveModel::Dirty](api.rubyonrails.org/classes/ActiveModel/Dirty.html)), performing a partial update of the document.

When the changed attributes are not available, performs full re-index of the record.

See the #update_document_attributes method for updating specific attributes directly.

Examples:

Update a document corresponding to the record


@article = Article.first
@article.update_attribute :title, 'Updated'
# SQL (0.3ms)  UPDATE "articles" SET "title" = ?...

@article.__elasticsearch__.update_document
# 2013-11-20 17:00:05 +0100: POST http://localhost:9200/articles/article/1/_update ...
# 2013-11-20 17:00:05 +0100: > {"doc":{"title":"Updated"}}

Parameters:

  • options (Hash) (defaults to: {})

    Optional arguments for passing to the client

Returns:

  • (Hash)

    The response from Elasticsearch

See Also:

[View source]

414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/elasticsearch/model/indexing.rb', line 414

def update_document(options={})
  if attributes_in_database = self.instance_variable_get(:@__changed_model_attributes).presence
    attributes = if respond_to?(:as_indexed_json)
      self.as_indexed_json.select { |k,v| attributes_in_database.keys.map(&:to_s).include? k.to_s }
    else
      attributes_in_database
    end

    unless attributes.empty?
      request = { index: index_name,
                  id:    self.id,
                  body:  { doc: attributes } }

      client.update(request.merge!(options))
    end
  else
    index_document(options)
  end
end