fix slow search
This commit is contained in:
48
src/migrations/20250326154214_precomputed_tsvector.sql
Normal file
48
src/migrations/20250326154214_precomputed_tsvector.sql
Normal file
@@ -0,0 +1,48 @@
|
||||
-- +goose Up
|
||||
-- +goose StatementBegin
|
||||
|
||||
|
||||
-- add the precomputed column
|
||||
ALTER TABLE documents ADD COLUMN content_tsv tsvector;
|
||||
|
||||
-- populate the new column with the initial data
|
||||
UPDATE documents SET content_tsv = to_tsvector('german', content);
|
||||
|
||||
-- Step 3: Create a trigger function to update the tsvector column upon insert or update
|
||||
CREATE OR REPLACE FUNCTION update_tsvector()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.content_tsv := to_tsvector('german', NEW.content);
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- create the trigger on the documents table
|
||||
CREATE TRIGGER documents_tsvector_update
|
||||
BEFORE INSERT OR UPDATE ON documents
|
||||
FOR EACH ROW EXECUTE FUNCTION update_tsvector();
|
||||
|
||||
-- create an index on the precomputed column for faster searches
|
||||
CREATE INDEX idx_fts_documents ON documents USING GIN(content_tsv);
|
||||
|
||||
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
-- +goose StatementBegin
|
||||
|
||||
|
||||
-- drop the trigger that updates the tsvector column
|
||||
DROP TRIGGER IF EXISTS documents_tsvector_update ON documents;
|
||||
|
||||
-- Step 2: Drop the trigger function
|
||||
DROP FUNCTION IF EXISTS update_tsvector();
|
||||
|
||||
-- Step 3: Drop the tsvector column
|
||||
ALTER TABLE documents DROP COLUMN IF EXISTS content_tsv;
|
||||
|
||||
-- Step 4: Drop the index on the tsvector column
|
||||
DROP INDEX IF EXISTS idx_fts_documents;
|
||||
|
||||
|
||||
-- +goose StatementEnd
|
||||
Reference in New Issue
Block a user