Sub topic 5
Matching Documents with `@@`
Assume you know basic SELECT, WHERE, and ORDER BY, and you can create PostgreSQL tables and indexes. This chapter uses the english text search configuration.
PostgreSQL matches a document against a search query with the @@ operator. The document is usually a tsvector, and the search query is a tsquery.
SELECT to_tsvector('english', 'The quick brown foxes jumped')
@@ to_tsquery('english', 'fox & jump') AS matches;Both values use the english configuration. PostgreSQL reduces related words to common lexemes: foxes becomes fox, and jumped becomes jump. The result is true because both lexemes occur in the document.
Build a `tsquery`
A tsquery represents search conditions. Its operators control how terms combine:
| Operator | Meaning | Example | Column | Column |
|---|---|---|---|---|
| `&` | Both terms must match | `fox & jump` | ||
| ` | ` | Either term may match | `fox | wolf` |
| `!` | The term must not match | `fox & !wolf` | ||
| `<->` | Terms must be adjacent | `quick <-> fox` |
You can inspect the query PostgreSQL creates:
SELECT to_tsquery('english', 'fox & jump') AS query;Use parentheses when combining operators to make the intended logic clear:
SELECT to_tsvector('english', 'A fox runs through the forest')
@@ to_tsquery('english', '(fox | wolf) & !cat') AS matches;The @@ operator can also appear with the query on the left:
SELECT to_tsquery('english', 'fox')
@@ to_tsvector('english', 'A fox runs') AS matches;The order does not change the meaning, but the conventional form puts the document first.
Understand positions and phrases
A tsvector stores lexemes and, when created normally, their positions. Positions allow PostgreSQL to evaluate phrase and proximity operators.
SELECT to_tsvector('english', 'The quick brown fox')
@@ to_tsquery('english', 'quick <-> brown <-> fox') AS matches;This returns true because the terms occur next to one another in that order. A phrase query can fail even when all terms exist if another word separates them.
The document and query should use compatible configurations. Different stemming or stop-word rules can produce different lexemes, causing an expected match to fail.
Exercise
What does to_tsvector('english', 'foxes jumped') @@ to_tsquery('english', 'fox & jump') return, and why?
Show answer
It returns true. The English configuration normalizes foxes to fox and jumped to jump, so both query lexemes occur in the document.