Skip to content

Commit 99b0f39

Browse files
nilbusestolfo
authored andcommitted
[MODEL] Avoid making an update when no attributes are changed (elastic#762)
Closes elastic#743
1 parent 735163a commit 99b0f39

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

elasticsearch-model/lib/elasticsearch/model/indexing.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ def delete_document(options={})
397397
# @see http://rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Actions:update
398398
#
399399
def update_document(options={})
400-
if attributes_in_database = self.instance_variable_get(:@__changed_model_attributes)
400+
if attributes_in_database = self.instance_variable_get(:@__changed_model_attributes).presence
401401
attributes = if respond_to?(:as_indexed_json)
402402
self.as_indexed_json.select { |k,v| attributes_in_database.keys.map(&:to_s).include? k.to_s }
403403
else

elasticsearch-model/test/unit/indexing_test.rb

+33
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,19 @@ def changes_to_save
176176
end
177177
end
178178

179+
class ::DummyIndexingModelWithNoChanges
180+
extend Elasticsearch::Model::Indexing::ClassMethods
181+
include Elasticsearch::Model::Indexing::InstanceMethods
182+
183+
def self.before_save(&block)
184+
(@callbacks ||= {})[block.hash] = block
185+
end
186+
187+
def changes_to_save
188+
{}
189+
end
190+
end
191+
179192
class ::DummyIndexingModelWithCallbacksAndCustomAsIndexedJson
180193
extend Elasticsearch::Model::Indexing::ClassMethods
181194
include Elasticsearch::Model::Indexing::InstanceMethods
@@ -393,6 +406,26 @@ def changes
393406
instance.update_document
394407
end
395408

409+
should "index instead of update when nothing was changed" do
410+
client = mock('client')
411+
instance = ::DummyIndexingModelWithNoChanges.new
412+
413+
# Set the fake `changes` hash
414+
instance.instance_variable_set(:@__changed_model_attributes, {})
415+
# Overload as_indexed_json for running index
416+
instance.expects(:as_indexed_json).returns({ 'foo' => 'BAR' })
417+
418+
client.expects(:index)
419+
client.expects(:update).never
420+
421+
instance.expects(:client).returns(client)
422+
instance.expects(:index_name).returns('foo')
423+
instance.expects(:document_type).returns('bar')
424+
instance.expects(:id).returns('1')
425+
426+
instance.update_document({})
427+
end
428+
396429
should "update only the specific attributes" do
397430
client = mock('client')
398431
instance = ::DummyIndexingModelWithCallbacks.new

0 commit comments

Comments
 (0)