Sub topic 7
Phrase and Proximity Search in PostgreSQL
Assume you know basic SELECT, WHERE, and PostgreSQL full-text search with tsvector, tsquery, and @@. This chapter focuses on controlling the distance and order between matching words.
Why word proximity matters
A query for database and index can match a document containing:
- “Database indexes improve query performance.”
- “The database stores customer data, while a separate service builds the index.”
- “Index the database before deployment.”
These matches do not have the same meaning. Phrase and proximity search lets you require words to appear next to each other or within a specific distance.
A tsquery phrase operator checks the positions stored in a tsvector:
<->requires adjacent positions in the specified order.<N>requires positions exactlyNapart. Therefore,<2>permits one lexeme between the two searched lexemes.
SELECT to_tsvector('english',
'PostgreSQL uses a GIN index for full text search')
@@ to_tsquery('english', 'gin <-> index') AS adjacent_match;
SELECT to_tsvector('english',
'PostgreSQL uses a GIN index for full text search')
@@ to_tsquery('english', 'gin <2> index') AS nearby_match;The first expression is false because gin and index are separated by one word. The second expression is true because their positions differ by two.
Building phrase queries from user input
Do not concatenate raw user input into to_tsquery. Its input must use tsquery syntax, and malformed or unexpected operators can change the query.
Use phraseto_tsquery when the user means an exact sequence of terms. It normalizes and stems the input using the selected configuration.
SELECT phraseto_tsquery('english', 'full text search') AS phrase_query;
SELECT id, title
FROM articles
WHERE search @@ phraseto_tsquery('english', 'full text search');phraseto_tsquery produces a phrase query using adjacency operators. It can also preserve the effect of stop words by using distance operators where needed.
For a search box that supports quoted phrases plus ordinary terms, websearch_to_tsquery is often a better choice:
SELECT websearch_to_tsquery(
'english',
'"full text" PostgreSQL -MySQL'
);Quoted text becomes a phrase requirement, while the leading minus excludes a term.
Visualizing the match
Phrase operators are stricter than &. Use & when terms may appear anywhere in the document. Use <-> or <N> when order and distance carry meaning.
Exercise
Which query matches the phrase “error handling” in that order, allowing no intervening lexeme?
Show answer
to_tsquery('english', 'error <-> handling'), or phraseto_tsquery('english', 'error handling') for raw phrase text.