Queues and background jobs
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:
1
2
3
4
5
6
7
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:
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 = client.init_index("index_name")
index.delete_object(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:
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 = client.init_index("index_name")
index.delete_object(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:
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