Sub topic 4
Queries as `tsquery`: `&`, `|`, `!`, and `<->`
This chapter assumes basic SQL, PostgreSQL tables and indexes, and experience running queries in psql or another SQL client. A tsquery is PostgreSQL's structured representation of a search request. It contains normalized lexemes, such as fox, rather than the original word forms.
Building a `tsquery`
Use to_tsquery when you need explicit search operators. The & operator means AND, | means OR, and ! means NOT:
SELECT to_tsquery('english', 'fox & jump') AS all_terms,
to_tsquery('english', 'fox | wolf') AS either_term,
to_tsquery('english', '!mysql') AS excluded_term,
to_tsquery('english', '(fox | wolf) & jump') AS grouped_query;The english configuration normalizes each term. For example, jump can match the stemmed form produced from jumped. Parentheses group expressions and make the intended logic clear.
The ! operator is unary, so it applies to the expression immediately after it. Use parentheses when negating a compound expression:
SELECT to_tsquery('english', 'fox & !(wolf | dog)');This query requires fox and rejects documents containing either wolf or dog.
Phrase and proximity search
The <-> operator requires two matching lexemes to occur next to each other in that order:
SELECT to_tsquery('english', 'full <-> text');For a longer phrase, chain the operator:
SELECT to_tsquery('english', 'full <-> text <-> search');PostgreSQL also supports a distance operator. <2> allows one position between the terms, while <3> allows up to two positions between them. These operators use positions stored in the document's tsvector.
SELECT to_tsquery('english', 'postgres <2> search');A phrase query is stricter than full & text. The AND query only checks that both lexemes exist somewhere in the document. The phrase query also checks their order and distance.
Matching a document
A tsquery becomes useful with the @@ operator:
SELECT to_tsvector('english', 'The fox jumped over the dog')
@@ to_tsquery('english', 'fox & jump') AS matches;Both sides should use compatible configurations. Otherwise, one side may stem or interpret words differently from the other.
Exercise
Which query requires the words “database” and “index” to be adjacent and in that order?
Show answer
to_tsquery('english', 'database <-> index').