phraseto_tsquery
PG 8.3+→ tsqueryConverts text to a tsquery that requires the words to appear in sequence (phrase search) using the <-> operator.
Signatures
phraseto_tsquery ( query text ) → tsqueryphraseto_tsquery ( config regconfig, query text ) → tsqueryParameters
| Parameter | Type | Description |
|---|---|---|
| config | regconfig | Text search configuration |
| query | text | Phrase to search for |
Examples
SELECT phraseto_tsquery('english', 'quick brown fox');'quick' <-> 'brown' <-> 'fox'SELECT * FROM articles WHERE tsv @@ phraseto_tsquery('english', 'machine learning');Articles with 'machine' immediately followed by 'learning'Words must appear in order with no gaps
SELECT phraseto_tsquery('english', 'full text search');'full' <-> 'text' <-> 'search'Only matches documents with these words in order
SELECT * FROM docs WHERE to_tsvector('english', content) @@ phraseto_tsquery('english', 'machine learning');(docs containing exact phrase)`plainto_tsquery('english', 'machine learning')` produces `'machin' & 'learn'` — it matches documents with both words anywhere, not necessarily adjacent. Use `phraseto_tsquery` when the exact sequence of words is required.
✓ Instead: -- Bad: matches docs with 'machine' and 'learning' anywhere, in any order SELECT * FROM docs WHERE tsv @@ plainto_tsquery('english', 'machine learning'); -- Good: requires adjacent sequence SELECT * FROM docs WHERE tsv @@ phraseto_tsquery('english', 'machine learning');
Use `phraseto_tsquery` when the user is searching for a specific phrase rather than individual words. This ensures 'machine learning' matches the compound term, not documents with 'machine' and 'learning' far apart.
SELECT * FROM docs WHERE tsv @@ phraseto_tsquery('english', 'primary key constraint');Documents with the exact phrase 'primary key constraint'