skip to content

In PostgreSQL, why should a help-centre search box pass user input to websearch_to_tsquery rather than to_tsquery, and what syntax does it accept?

level: middleimportance: should knowfreq 46%

answer

  1. operator syntax versus raw text
  2. error 42601 on bare words
  3. quotes, or, leading dash
  4. never raises, no prefix

basics

~20 s

to_tsquery expects tsquery operator syntax and raises a syntax error on ordinary input such as two bare words. websearch_to_tsquery never raises: plain words are ANDed, quoted text becomes a phrase, 'or' becomes OR and a dash becomes NOT.

solid answer

~40 s

`to_tsquery` wants tokens already joined by `&`, `|`, `!` or `<->`, so `to_tsquery('english', 'reset password')` fails with `syntax error in tsquery` (SQLSTATE `42601`), and a stray parenthesis can do the same. `websearch_to_tsquery('english', input)` accepts search-box syntax and never raises: unquoted words are ANDed as in `plainto_tsquery`, `"quoted text"` becomes a `<->` phrase as in `phraseto_tsquery`, the word `or` becomes `|`, a dash becomes `!`, and other punctuation is ignored. It does not honour `:*` prefixes or weight labels, so type-ahead needs another route. Input made only of stop words, such as `how to`, yields an empty `tsquery` that matches nothing, which the application can detect with `numnode()`. Always pass the configuration explicitly and bind the input as a parameter.

code

sql · 11 lines
sql
SELECT to_tsquery('english', 'reset password');
-- ERROR:  syntax error in tsquery: "reset password"

SELECT websearch_to_tsquery('english', '"reset password" -email');
-- 'reset' <-> 'password' & !'email'

SELECT websearch_to_tsquery('english', 'sso or saml');
-- 'sso' | 'saml'

SELECT numnode(websearch_to_tsquery('english', 'how to'));
-- 0  (only stop words: the query matches nothing)

go deeper

for a junior

Remember that to_tsquery needs operators between words and fails on plain text, while websearch_to_tsquery takes what a user types.

for a middle

Explain the four constructors side by side and what websearch_to_tsquery maps: quotes to <->, or to |, a dash to !. Mention that it ignores :* and weights.

for a senior

Show the production edges: SQLSTATE 42601 from an unguarded endpoint, stop-word-only queries and numnode(), matching the configuration to the stored tsvector, and a safe prefix strategy for type-ahead.

for a principal

Treat the search-box contract as an API decision: which syntax users get, how empty and failing queries degrade, and when type-ahead or typo tolerance justifies trigram search or a separate search service.

## Four ways to turn text into a tsquery PostgreSQL full-text search matches a **`tsvector`** (the processed document) against a **`tsquery`** (the processed question). The question comes from a user typing into a help-centre search box, so the function that builds the `tsquery` decides whether the search is robust or throws errors at the user. All four functions normalise each word with a text search configuration exactly as `to_tsvector` does (stop words dropped, words stemmed); they differ in how they read the input: | Function | Reads input as | Operators honoured | Malformed input | |---|---|---|---| | `to_tsquery` | tsquery syntax | `&`, `\|`, `!`, `<->`, `<N>`, `:*`, weights | raises `syntax error in tsquery` | | `plainto_tsquery` | plain text | none; ANDs all surviving words | punctuation discarded | | `phraseto_tsquery` | plain text | none; chains words with `<->` | punctuation discarded | | `websearch_to_tsquery` | search-engine style text | quotes, `or`, leading `-` | never raises | ## Why to_tsquery is the wrong door for raw input `to_tsquery` expects its argument to *already* be a tsquery expression. Two words without an operator between them are a syntax error: - `to_tsquery('english', 'reset password')` fails with `ERROR: syntax error in tsquery: "reset password"`; - the error carries SQLSTATE **`42601`** (`syntax_error`), so an unguarded search endpoint turns ordinary typing into a server error; - parentheses, colons and `&` typed by users are interpreted as operators, which gives surprising results even when the parse succeeds. `to_tsquery` stays useful when the application *builds* the expression itself, for example appending `:*` for prefix matching after whitelisting the user's words. ## What websearch_to_tsquery accepts `websearch_to_tsquery` was designed for raw user input and **never raises a syntax error**. Its grammar is small: 1. **Unquoted words** are joined with `&`, as `plainto_tsquery` would do. 2. **`"quoted text"`** becomes a phrase joined with `<->`, as `phraseto_tsquery` would do. 3. The word **`or`** becomes the `|` operator. 4. A **dash** before a term or a quoted phrase becomes `!` (NOT). 5. All other punctuation is ignored. So `"reset password" -email` becomes `'reset' <-> 'password' & !'email'`, and `sso or saml` becomes `'sso' | 'saml'`. Input such as `""" )( dummy` degrades to whatever words survive instead of failing. ## The edges you still have to handle - **No prefix matching.** Like `plainto_tsquery`, it ignores `:*` and weight labels typed by the user. Type-ahead needs either a `to_tsquery` string built by the application from sanitised words with `:*` on the last one, or trigram matching with `pg_trgm`. - **Stop words inside quotes.** A quoted phrase is processed as `phraseto_tsquery` would: stop words are not simply dropped but counted with a `<N>` operator, so `"reset your password"` becomes `'reset' <2> 'password'` and still demands the original spacing. - **Stop-word-only input.** `how to` contains only English stop words, so the result is an empty `tsquery`. An empty query matches nothing; `numnode(query) = 0` lets the application show a hint or fall back to a title search instead of an empty page. - **The configuration argument.** Without it, `default_text_search_config` decides how the query is normalised. If the stored `tsvector` was built with `english` and the session default is `simple`, the query keeps `passwords` unstemmed and silently misses documents. Pass the same configuration the documents were built with. - **SQL injection is a separate problem.** `websearch_to_tsquery` makes the *tsquery* parse safe; it does nothing for SQL built by string concatenation. Bind the user's text as a parameter. ## A reasonable search-box query The common shape is `WHERE search_tsv @@ websearch_to_tsquery('english', $1)`, with `$1` bound by the driver, the configuration matching the one used to build `search_tsv`, and an index on `search_tsv` (the index itself is covered with PostgreSQL's GIN and GiST indexes). When an interviewer asks why, the answer is three facts: **raw input breaks `to_tsquery`, `websearch_to_tsquery` cannot be broken by input, and it still lets users express phrases, OR and exclusion.**

  • What happens when a user searches for nothing but stop words, such as 'how to'?
    Every word is removed during normalisation, so `websearch_to_tsquery` returns an empty `tsquery`, and an empty query matches no document. Check `numnode(query) = 0` before running the search and show a hint, or fall back to a trigram match on titles, rather than returning an unexplained empty page.
  • How do you offer prefix type-ahead when websearch_to_tsquery ignores :*?
    Build the expression in the application: keep only word characters from each typed word, join them with `&`, append `:*` to the last one and pass the string, as a bound parameter, to `to_tsquery('english', ...)`. Because the application controls the syntax, it cannot raise. For misspelled fragments, `pg_trgm` word similarity on titles is the alternative.
  • Why pass the configuration argument instead of relying on default_text_search_config?
    The query's lexemes must be normalised exactly like the stored `tsvector`. The one-argument form uses the session's `default_text_search_config` (built-in default `pg_catalog.simple`, usually overwritten by `initdb` from `lc_ctype`), so a client or role with a different setting stems differently and silently misses matches.

  • to_tsquery is safe for raw input because it ignores punctuation.
  • websearch_to_tsquery supports prefix search when the user types word:*.
  • plainto_tsquery understands quoted phrases and minus signs.
  • A query made only of stop words matches every article.
  • websearch_to_tsquery also protects concatenated SQL from injection.