Sub topic 2
Turning User Input into a tsquery Safely
This chapter assumes you know basic SQL, can create a table with a tsvector column, and have a GIN index on that column. The examples use the articles table from the previous chapter, with title, body, and a stored search column.
Why raw input breaks to_tsquery
to_tsquery expects tsquery syntax, where &, |, !, and <-> are operators. If a user types C++ & friends or an unbalanced quote, the function raises a syntax error. Pass user text to one of the constructor functions instead:
SELECT
websearch_to_tsquery('english', 'postgres "full text" -mysql') AS web_query,
plainto_tsquery('english', 'full text search') AS plain_query,
phraseto_tsquery('english', 'full text search') AS phrase_query;websearch_to_tsquery understands quotes, OR, and a leading minus, and it never raises a syntax error for ordinary input. plainto_tsquery joins all terms with &. phraseto_tsquery requires the terms to appear next to each other.
Phrase and proximity search
The <-> operator means "immediately followed by," and <N> means "within N positions." Use these when word order or closeness matters:
SELECT id, title
FROM articles
WHERE search @@ to_tsquery('english', 'full <-> text');
SELECT id, title
FROM articles
WHERE search @@ to_tsquery('english', 'full <3> search');Weighting title over body with setweight
The stored column in the previous chapter gives the title weight A and the body weight B. Ranking functions treat A as more important than B. Check the weights on a sample value:
SELECT setweight(to_tsvector('english', 'Full text search'), 'A')
|| setweight(to_tsvector('english', 'Ranking and headlines'), 'B');Ranking with ts_rank and ts_rank_cd
ts_rank scores how often query terms appear, weighted by their labels. ts_rank_cd (cover density) also rewards matches that sit close together, so it suits phrase-style queries better.
SELECT a.id,
a.title,
ts_rank(a.search, q.query) AS rank,
ts_rank_cd(a.search, q.query) AS cover_rank
FROM articles AS a,
websearch_to_tsquery('english', 'full text search') AS q(query)
WHERE a.search @@ q.query
ORDER BY rank DESC
LIMIT 10;Highlighting matches with ts_headline
ts_headline works on the original text, not the tsvector, and wraps matches in the markers you choose. Run it only on the rows you display:
SELECT ts_headline('english', a.body, q.query,
'StartSel=<mark>, StopSel=</mark>, MaxWords=35, MinWords=15') AS snippet
FROM articles AS a,
websearch_to_tsquery('english', 'full text search') AS q(query)
WHERE a.search @@ q.query
LIMIT 10;Exercise
Exercise
Why does websearchtotsquery('english', 'cats -dogs') remove matches containing "dogs", while to_tsquery('english', 'cats & dogs') returns rows with both words?
Show answer
The leading minus in websearchtotsquery negates "dogs," so rows containing "dogs" are excluded. The to_tsquery expression uses &, which requires both "cats" and "dogs" to match, not exclusion.