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.
Code
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
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.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- Which tables appear in this script?
- `articles`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.