Skip to content

Commit 91b22ca

Browse files
update search index (#89)
1 parent ba07a45 commit 91b22ca

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

app/models/document.rb

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ class Document < ApplicationRecord
77
pg_search_scope :search_by_title_and_document,
88
against: %i[title document],
99
using: {
10-
tsearch: { prefix: true } # This option allows partial matches
10+
tsearch: { prefix: true, dictionary: 'english',
11+
tsvector_column: 'search_vector' } # This option allows partial matches
1112
}
1213

1314
has_neighbors :embedding
@@ -34,6 +35,7 @@ class Document < ApplicationRecord
3435

3536
after_save :sync_quip_doc_if_needed
3637
after_commit :schedule_embed_document_job, if: -> { previous_changes.include?('check_hash') }
38+
before_save :update_search_vector
3739

3840
def source_type
3941
if source_url.include?('quip.com')
@@ -105,4 +107,17 @@ def schedule_embed_document_job
105107
# Set the priority and delay, and queue the job if the check_hash has changed
106108
EmbedDocumentJob.set(priority: 5, wait: delay_seconds.seconds).perform_later(id)
107109
end
110+
111+
def update_search_vector
112+
# Properly updates the tsvector column using raw SQL
113+
sanitized_sql = Document.sanitize_sql([
114+
"to_tsvector('english', coalesce(?, '') || ' ' || coalesce(?, ''))",
115+
title,
116+
document
117+
])
118+
119+
self.search_vector = Document.connection.execute(
120+
"SELECT #{sanitized_sql} AS tsvector"
121+
).first['tsvector']
122+
end
108123
end
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
class AddSearchVector < ActiveRecord::Migration[7.1]
2+
def change
3+
add_column :documents, :search_vector, :tsvector
4+
add_index :documents, :search_vector, using: :gin
5+
end
6+
end

db/schema.rb

Lines changed: 3 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)