Integrations / Frameworks / Rails / Queues & Background Jobs
Mar. 18, 2019

Queues & Background Jobs

You can configure the auto-indexing & auto-removal process to use a queue to perform those operations in background. ActiveJob (Rails >=4.2) queues are used by default but you can define your own queuing mechanism:

1
2
3
4
5
6
7
class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch enqueue: true do # ActiveJob will be triggered using a `algoliasearch` queue
    attribute :first_name, :last_name, :email
  end
end

Things to Consider

If you are performing updates & deletions in the background, then a record deletion can be committed to your database prior to the job actually executing. Thus, if you were to load the record to remove it from the database, then your ActiveRecord#find will fail with a RecordNotFound.

In this case you can bypass loading the record from ActiveRecord and just communicate with the index directly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
      index = Algolia::Index.new("index_name")
      index.delete_object(id)
    else
      # the record should be present
      c = Contact.find(id)
      c.index!
    end
  end
end

With Sidekiq

If you’re using Sidekiq:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
      index = Algolia::Index.new("index_name")
      index.delete_object(id)
    else
      # the record should be present
      c = Contact.find(id)
      c.index!
    end
  end
end

With DelayedJob

If you’re using delayed_job:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

Did you find this page helpful?