Module: Elasticsearch::Model::Indexing::InstanceMethods
- Defined in:
- lib/elasticsearch/model/indexing.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#delete_document(options = {}) ⇒ Hash
Deletes the model instance from the index.
-
#index_document(options = {}) ⇒ Hash
Serializes the model instance into JSON (by calling ‘as_indexed_json`), and saves the document into the Elasticsearch index.
-
#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.
Class Method Details
.included(base) ⇒ Object
251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
# File 'lib/elasticsearch/model/indexing.rb', line 251 def self.included(base) # Register callback for storing changed attributes for models # which implement `before_save` and `changed_attributes` methods # # @note This is typically triggered only when the module would be # included in the model directly, not within the proxy. # # @see #update_document # base.before_save do |instance| instance.instance_variable_set(:@__changed_attributes, Hash[ instance.changes.map { |key, value| [key, value.last] } ]) end if base.respond_to?(:before_save) && base.instance_methods.include?(:changed_attributes) end |
Instance Method Details
#delete_document(options = {}) ⇒ Hash
Deletes the model instance from the index
304 305 306 307 308 309 310 |
# File 'lib/elasticsearch/model/indexing.rb', line 304 def delete_document(={}) client.delete( { index: index_name, type: document_type, id: self.id }.merge() ) end |
#index_document(options = {}) ⇒ Hash
Serializes the model instance into JSON (by calling ‘as_indexed_json`), and saves the document into the Elasticsearch index.
280 281 282 283 284 285 286 287 288 289 |
# File 'lib/elasticsearch/model/indexing.rb', line 280 def index_document(={}) document = self.as_indexed_json client.index( { index: index_name, type: document_type, id: self.id, body: document }.merge() ) end |
#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.
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
# File 'lib/elasticsearch/model/indexing.rb', line 334 def update_document(={}) if changed_attributes = self.instance_variable_get(:@__changed_attributes) attributes = if respond_to?(:as_indexed_json) changed_attributes.select { |k,v| self.as_indexed_json.keys.include? k } else changed_attributes end client.update( { index: index_name, type: document_type, id: self.id, body: { doc: attributes } }.merge() ) else index_document() end end |