Tsquery Prefix Match For Autocomplete

Match word stems still being typed with to_tsquery's :* prefix suffix, so data:* finds data and databases for autocomplete-style search.

SqlData Fetching

Code

snippet
CREATE TABLE articles (
    id   int PRIMARY KEY,
    body text NOT NULL
);

INSERT INTO articles VALUES
    (1, 'Data pipelines for analytics'),
    (2, 'Database connection pooling'),
    (3, 'Read replicas and failover');

-- 前缀匹配(prefix matching):to_tsquery 的 data:* 命中 data、databases
-- 等同前缀词素,适合输入到一半时的自动补全
SELECT id
FROM articles
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'data:*');

How the snippet works

SELECT / INSERT / CREATE statements share the script, touching articles.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the articles table.

Statements that matter

SELECT id
FROM articles
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'data:*');
INSERT INTO articles VALUES
    (1, 'Data pipelines for analytics'),
    (2, 'Database connection pooling'),
    (3, 'Read replicas and failover');
CREATE TABLE articles (
    id   int PRIMARY KEY,
    body text NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`articles`.