ruby
39 lines · 9 steps
Keeping a search index fresh in Rails
An Article model uses after_commit callbacks and a debounced job to keep an external search index in sync only when meaningful fields change.
Explained by
highlit
1class Article < ApplicationRecord
2 belongs_to :author
3 has_many :taggings, dependent: :destroy
4 has_many :tags, through: :taggings
5
6 INDEX_DEBOUNCE = 5.minutes
7
8 after_commit :schedule_search_reindex, on: %i[create update]
9 after_commit :remove_from_search_index, on: :destroy
10
11 scope :pending_reindex, -> { where("indexed_at IS NULL OR indexed_at < updated_at") }
12
13 def search_index_stale?
14 indexed_at.nil? || indexed_at < updated_at
15 end
16
17 def mark_indexed!
18 update_column(:indexed_at, Time.current)
19 end
20
21 private
22
23 def schedule_search_reindex
24 return unless search_index_stale?
25 return unless saved_change_to_indexable_attributes?
26
27 ReindexArticleJob
28 .set(wait: INDEX_DEBOUNCE)
29 .perform_later(id)
30 end
31
32 def remove_from_search_index
33 RemoveFromSearchIndexJob.perform_later(self.class.name, id)
34 end
35
36 def saved_change_to_indexable_attributes?
37 (saved_changes.keys & %w[title body summary published_at author_id]).any?
38 end
39end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1after_commit runs jobs only after the transaction succeeds, so you never enqueue work for a rollback.
- 2Guarding reindexing behind a whitelist of changed columns avoids wasteful work on irrelevant updates.
- 3Debouncing job enqueues with a wait window collapses rapid edits into a single reindex.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/keeping-a-search-index-fresh-in-rails-explained-ruby-86a7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.