Skip to content

[MODEL] Avoid making an update when no attributes are changed #762

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion elasticsearch-model/lib/elasticsearch/model/indexing.rb
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ def delete_document(options={})
# @see http://rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Actions:update
#
def update_document(options={})
if attributes_in_database = self.instance_variable_get(:@__changed_model_attributes)
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
Expand Down
33 changes: 33 additions & 0 deletions elasticsearch-model/test/unit/indexing_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,19 @@ def changes_to_save
end
end

class ::DummyIndexingModelWithNoChanges
extend Elasticsearch::Model::Indexing::ClassMethods
include Elasticsearch::Model::Indexing::InstanceMethods

def self.before_save(&block)
(@callbacks ||= {})[block.hash] = block
end

def changes_to_save
{}
end
end

class ::DummyIndexingModelWithCallbacksAndCustomAsIndexedJson
extend Elasticsearch::Model::Indexing::ClassMethods
include Elasticsearch::Model::Indexing::InstanceMethods
Expand Down Expand Up @@ -393,6 +406,26 @@ def changes
instance.update_document
end

should "index instead of update when nothing was changed" do
client = mock('client')
instance = ::DummyIndexingModelWithNoChanges.new

# Set the fake `changes` hash
instance.instance_variable_set(:@__changed_model_attributes, {})
# Overload as_indexed_json for running index
instance.expects(:as_indexed_json).returns({ 'foo' => 'BAR' })

client.expects(:index)
client.expects(:update).never

instance.expects(:client).returns(client)
instance.expects(:index_name).returns('foo')
instance.expects(:document_type).returns('bar')
instance.expects(:id).returns('1')

instance.update_document({})
end

should "update only the specific attributes" do
client = mock('client')
instance = ::DummyIndexingModelWithCallbacks.new
Expand Down