Skip to main content
To perform auto-indexing in the background, use queues.

Background jobs with ActiveJob

By default, ActiveJob queues are used, but you can define your own queueing mechanism:
Ruby
class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch enqueue: true do
    attribute :first_name, :last_name, :email
  end
end
If you perform updates and deletions in the background, you can commit a record to your database before running the job. If you load a record before the job runs, the call to ActiveRecord#find fails with a RecordNotFound error. To prevent this, you can bypass loading the record from the ActiveRecord and directly communicate with the index:
Ruby
class MySidekiqWorker
  def perform(id, remove)
    if remove
      # the record has likely already been removed from your database so we cannot
      # use ActiveRecord#find to load it
      task = client.delete_objects(Contact.index_name, [id])
      client.wait_for_task(task.task_id)
    else
      # the record should be present
      c = Contact.find(id)
      c.index!
    end
  end
end

Background jobs with Sidekiq

You can process jobs in the background with Sidekiq:
Ruby
class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch enqueue: :trigger_sidekiq_worker do
    attribute :first_name, :last_name, :email
  end

  def self.trigger_sidekiq_worker(record, remove)
    MySidekiqWorker.perform_async(record.id, remove)
  end
end

class MySidekiqWorker
  def perform(id, remove)
    if remove
      # the record has likely already been removed from your database so we cannot
      # use ActiveRecord#find to load it
      task = client.delete_objects(Contact.index_name, [id])
      client.wait_for_task(task.task_id)
    else
      # the record should be present
      c = Contact.find(id)
      c.index!
    end
  end
end

Background jobs with delayed_job

You can process jobs in the background with delayed_job:
Ruby
class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch enqueue: :trigger_delayed_job do
    attribute :first_name, :last_name, :email
  end

  def self.trigger_delayed_job(record, remove)
    if remove
      record.delay.remove_from_index!
    else
      record.delay.index!
    end
  end
end
I