websearch_to_tsquery User Query Parsing

Parse user-typed search strings with websearch_to_tsquery, which tolerates quoted phrases, OR, and -excluded terms without failing.

SqlData Fetching

Code

snippet
-- websearch_to_tsquery parses user-typed input with forgiveness:
-- "quoted phrase" for phrases, OR for alternation, -word for exclusion; malformed input never raises
CREATE TABLE articles (
    article_id    int PRIMARY KEY,
    title         text NOT NULL,
    search_vector tsvector NOT NULL
);

INSERT INTO articles VALUES
    (1, 'Backup and restore', to_tsvector('english', 'Backup point in time restore for postgres clusters')),
    (2, 'Deprecated backup guide', to_tsvector('english', 'Old backup procedure, deprecated in 2023')),
    (3, 'Replication overview', to_tsvector('english', 'Streaming replication setup and failover'));

-- one input uses all three syntaxes: backup or replication, the phrase "point in time", and -deprecated as exclusion
SELECT article_id, title,
       ts_rank(search_vector, websearch_to_tsquery('english', 'backup or replication "point in time" -deprecated')) AS rank
FROM articles
WHERE search_vector @@ websearch_to_tsquery('english', 'backup or replication "point in time" -deprecated')
ORDER BY rank DESC;

How it works

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

Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Putting it to use

Run the statement against the articles table.

Core lines

SELECT article_id, title,
       ts_rank(search_vector, websearch_to_tsquery('english', 'backup or replication "point in time" -deprecated')) AS rank
FROM articles
WHERE search_vector @@ websearch_to_tsquery('english', 'backup or replication "point in time" -deprecated')
ORDER BY rank DESC;
CREATE TABLE articles (
    article_id    int PRIMARY KEY,
    title         text NOT NULL,
    search_vector tsvector NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`articles` — referenced directly, no join needed.