tsvector GIN Index Full Text Search

Combine a stored tsvector generated column with a GIN index so websearch_to_tsquery queries rank matching articles without scanning every row.

SqlData Fetching

Code

snippet
-- 全文检索三件套:tsvector 生成列 + GIN 索引 + tsquery 匹配
-- 标题权重 A、正文默认权重,STORED 让结果写库时算好、查询直接用
CREATE TABLE articles (
    id     bigserial PRIMARY KEY,
    title  text NOT NULL,
    body   text NOT NULL,
    search tsvector GENERATED ALWAYS AS
        (setweight(to_tsvector('english', title), 'A') || to_tsvector('english', body)) STORED
);

CREATE INDEX idx_articles_search ON articles USING GIN (search);

INSERT INTO articles (title, body) VALUES
    ('Retry Backoff', 'Handle transient failures with exponential backoff and jitter.'),
    ('Rate Limiting', 'Token bucket algorithm keeps request bursts bounded.');

-- websearch_to_tsquery 贴近用户书写习惯:空格=and、or、-前缀=排除,坏拼写也不抛错
SELECT title,
       ts_rank(search, websearch_to_tsquery('english', 'backoff -bucket')) AS score
FROM articles
WHERE search @@ websearch_to_tsquery('english', 'backoff -bucket')
ORDER BY score DESC;

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with articles among the objects involved.

What the statements actually assemble: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Using it

Run the statement against the articles table.

Key statements

INSERT INTO articles (title, body) VALUES
('Retry Backoff', 'Handle transient failures with exponential backoff and jitter.'),
('Rate Limiting', 'Token bucket algorithm keeps request bursts bounded.');
SELECT title,
ts_rank(search, websearch_to_tsquery('english', 'backoff -bucket')) AS score
FROM articles
WHERE search @@ websearch_to_tsquery('english', 'backoff -bucket')
ORDER BY score DESC;
CREATE TABLE articles (
id     bigserial PRIMARY KEY,
title  text NOT NULL,
body   text NOT NULL,
search tsvector GENERATED ALWAYS AS
(setweight(to_tsvector('english', title), 'A') || to_tsvector('english', body)) STORED
);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `articles`.