Skip to content

Commit

Permalink
Chore: Speed up admin learner search (#4918)
Browse files Browse the repository at this point in the history
Because:
- The default configuration is not fast enough for the amount of data we
have in production.

This commit:
- Adds a ts_vector column to the users table which we can search against
- this is recommended in the [pg_search
docs](https://github.com/Casecommons/pg_search?tab=readme-ov-file#using-tsvector-columns)
- Sneaks in a data-turbo-action="advance" attribute to the learner
search results turbo frame so we can share search result pages with
admins if we need to.
  • Loading branch information
KevinMulhern authored Feb 12, 2025
1 parent b5788af commit 403dc98
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 3 deletions.
15 changes: 14 additions & 1 deletion app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,20 @@ class User < ApplicationRecord
scope :signed_up_on, ->(date) { where(created_at: date.all_day) }
scope :banned, -> { where(banned: true) }

pg_search_scope :search_by, against: %i[username email], using: { tsearch: { prefix: true } }
pg_search_scope(
:search_by,
against: %i[
username
email
],
using: {
tsearch: {
prefix: true,
dictionary: 'english',
tsvector_column: 'search_tsvector'
}
}
)

def progress_for(course)
@progress ||= Hash.new { |hash, c| hash[c] = CourseProgress.new(c, self) }
Expand Down
2 changes: 1 addition & 1 deletion app/views/admin/learners/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<%= inline_svg_tag 'icons/magnifying-glass.svg', class: 'pointer-events-none col-start-1 row-start-1 ml-3 size-5 self-center text-gray-400' %>
<% end %>

<%= turbo_frame_tag :learner_results, target: '_top' do %>
<%= turbo_frame_tag :learner_results, target: '_top', data: { turbo_action: 'advance' } do %>
<div class="mt-8 flow-root">
<% if @learners.any? %>
<div class="-mx-4 -my-2 overflow-x-auto sm:-mx-6 max-w-6xl px-6" data-test-id="learners-list">
Expand Down
15 changes: 15 additions & 0 deletions db/migrate/20250212143446_add_search_ts_vector_column_to_users.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class AddSearchTsVectorColumnToUsers < ActiveRecord::Migration[7.1]
disable_ddl_transaction!

def change
execute <<-SQL.squish
ALTER TABLE users
ADD COLUMN search_tsvector tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(email, '')), 'A') ||
setweight(to_tsvector('english', coalesce(username,'')), 'B')
) STORED;
SQL

add_index :users, :search_tsvector, using: :gin, algorithm: :concurrently
end
end
4 changes: 3 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 403dc98

Please sign in to comment.