diff --git a/elasticsearch-model/lib/elasticsearch/model/indexing.rb b/elasticsearch-model/lib/elasticsearch/model/indexing.rb index 39ad06bc3..0763f1c2b 100644 --- a/elasticsearch-model/lib/elasticsearch/model/indexing.rb +++ b/elasticsearch-model/lib/elasticsearch/model/indexing.rb @@ -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 diff --git a/elasticsearch-model/test/unit/indexing_test.rb b/elasticsearch-model/test/unit/indexing_test.rb index e3bfad868..c3836e5cb 100644 --- a/elasticsearch-model/test/unit/indexing_test.rb +++ b/elasticsearch-model/test/unit/indexing_test.rb @@ -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 @@ -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