Elasticsearch-rails: Elasticsearch-rails with soft destroy

Created on 22 Apr 2016  路  4Comments  路  Source: elastic/elasticsearch-rails

Soft deletes using https://github.com/radar/paranoia.

I'm currently using gem which adds paranoia to the models. When destroy is called on a model it updates the deleted_at column to the time deleted rather than removing from the database. Elasticsearch::Model::Callbacks isn't picking up on this soft destroy. The elasticsearch document doesn't remove or get updated to the deleted_at date. (the field does exist on the index)

Most helpful comment

Very useful info here, thanks guys. I was having issues with a soft deletion gem too and implementing my own callbacks (and not using Elasticsearch::Model::Callbacks) has solved it

All 4 comments

I ended up doing this as a workaround. I tied into the paranoia gem events to perform the needed functions. Notice that i didn't include Elasticsearch::Model::Callbacks. This is because it interfered with my hooks on update. My update_document function would be called first and set the correct value for 'deleted_at' in elasticsearch, but the Elasticsearch::Model::Callbacks module would call it again and the document 'deleted_at' would be set back to null for some reason.

module Callbackable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model

      after_create :index_document
      after_destroy :update_document
      after_restore :update_document
      after_really_destroy :delete_document

      def index_document
        self.__elasticsearch__.index_document
      end

      def update_document
        self.__elasticsearch__.update_document
      end

      def delete_document
        self.__elasticsearch__.delete_document
      end
  end
end

Hi, so the first thing to note is that the Elasticsearch::Model::Callbacks module is really only a _starting point_ for people to quickly lift the application off the ground. In case of something like soft-delete, it's best to implement your own callbacks, which would set something like deleted:true, and you'd have a filter on that property in your searches. I bet it would be possible to make it work in tandem with the paranoid gem, ie. ussing the deleted_at attribute.

Very useful info here, thanks guys. I was having issues with a soft deletion gem too and implementing my own callbacks (and not using Elasticsearch::Model::Callbacks) has solved it

@skukx, that's a great solution. I'm gonna close the issue then!

Was this page helpful?
0 / 5 - 0 ratings