Trigger Keeps The TSVector In Sync
A BEFORE trigger recomputes the tsvector on title or body changes, keeping search hits in step with edits on the same statement.
Code
CREATE TABLE help_articles (
id int GENERATED ALWAYS AS IDENTITY,
title text NOT NULL,
body text NOT NULL,
search tsvector
);
-- 生成列不能跨行/跨表取值;来源需要那种逻辑时由触发器维护 tsvector 列
CREATE OR REPLACE FUNCTION articles_search_refresh() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.search := setweight(to_tsvector('english', NEW.title), 'A')
|| to_tsvector('english', NEW.body);
RETURN NEW;
END;
$$;
-- UPDATE OF 列清单:title/body 不变的其他 UPDATE 不触发重算
CREATE TRIGGER articles_search_biu
BEFORE INSERT OR UPDATE OF title, body ON help_articles
FOR EACH ROW EXECUTE FUNCTION articles_search_refresh();
INSERT INTO help_articles (title, body) VALUES
('Retry Backoff', 'Exponential backoff with jitter.');
-- 改标题和正文后向量随 UPDATE 重算:backoff 立刻搜不到,exponential 立刻可搜
UPDATE help_articles SET title = 'Exponential Retry', body = 'Wait longer after each failure.';
SELECT
title,
search @@ to_tsquery('english', 'backoff') AS old_word_still_hits,
search @@ to_tsquery('english', 'exponential') AS new_word_hits
FROM help_articles;Inside the snippet
The file runs SELECT / INSERT / UPDATE / CREATE statements, touching of and help_articles.
Breaking the statements into their working parts: NOT NULL qualifiers on the required columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
Run the statement against the of table.
Core lines
CREATE TRIGGER articles_search_biu
BEFORE INSERT OR UPDATE OF title, body ON help_articles
FOR EACH ROW EXECUTE FUNCTION articles_search_refresh();
INSERT INTO help_articles (title, body) VALUES
('Retry Backoff', 'Exponential backoff with jitter.');
CREATE OR REPLACE FUNCTION articles_search_refresh() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.search := setweight(to_tsvector('english', NEW.title), 'A')
|| to_tsvector('english', NEW.body);
RETURN NEW;
END;
$$;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- `of`, `help_articles`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.