Callback after update index on elastic search using chewy

977 views Asked by At

Suppose that I have the following code:

class User < ActiveRecord::Base
  update_index('users#user') { self } 
                                      

  after_commit :send_socket_event, on: %i[create update]
  

  def send_socket_event(self):
     SockeClient.send(self)
  end
end

The socket event is sent to the client then the client creates an http request to get the new user information from an endpoint that makes a query to elastic search. My problem is that the response is done before that the index on ES is updated so the information in the endpoint response isn't already updated.

I wonder if there is something like a callback after index for the Chewy::Index class.

1

There are 1 answers

0
Milind On

I have not used chewy but did used searchkick to a large extent.

So by using searchkick, i would use the reindex and remove_from_index callback, to trigger whatever I wanted.

For example - in below code snippet, I create a module and then include it it any model that I want to use these methods, I am checking something after reindexing is done or something is removed from index

    ##check a model attribute or call function, here I am just checking some attribute.
    after_save :reindex , if: Proc.new { |vendor| vendor.accepted? }
    after_save :remove_from_index , if: Proc.new { |vendor| !vendor.accepted? }

    ####where remove_from_index was just a simple method in a module, so I just include this module in any model
    def remove_from_index
      self.class.name.classify.constantize.searchkick_index.remove(self)
    end