to_tsquery parses text into a tsquery value for PostgreSQL full-text search. Use it when a search needs explicit Boolean logic, phrase matching, or proximity instead of requiring every generated lexeme. section 6.3.2
Build querytext with operators and grouping:
- & requires both terms; | accepts either term; ! excludes a term or phrase; and <-> requires terms to be followed by one another. section 6.3.2
- Group alternatives with parentheses, as in computer & animated & (lion | clownfish | donkey). section 6.3.2
- Pass an optional regconfig argument when the search requires a full-text configuration other than the default. section 6.3.2
Combine alternatives in a movie search
SELECT id, name FROM omdb.movies WHERE lexemes @@ to_tsquery('computer & animated & (lion | clownfish | donkey)'); The query returns Finding Nemo, Shrek, and The Lion King. It requires computer and animated while accepting any one of the three animal terms. section 6.3.2
Exclude a phrase and require proximity
SELECT id, name FROM omdb.movies WHERE lexemes @@ to_tsquery('lion & !''The Lion King'''); The phrase is represented as !( 'lion' <-> 'king' ). For ordered proximity, use a distance operator such as return <3> king, which matches The Lord of the Rings: The Return of the King. section 6.3.2
to_tsquery([ config regconfig, ] querytext text) returns tsquery
Inspect the function signature while composing advanced tsquery expressions. section 6.3.2
