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.

SqlData Integrity

Code

snippet
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

FAQ

What objects does the SQL involve?
`of`, `help_articles`.