Sub topic 7
Phrase and proximity search
This chapter assumes you can build a tsvector and a tsquery and match them with @@. It covers the <-> and <N> operators, how phrase queries behave around stop words and punctuation, and how to approximate "within N words" matching.
Why `&` is not enough
A query like full & text & search matches any document that contains all three lexemes, in any order and at any distance. A document that says "Search the archive for full records, and add some text" matches too, although it is not about full-text search.
Phrase search adds a position constraint. Every lexeme in a tsvector carries the positions where it occurred, and phrase operators compare those positions.
The follows-by operator `<->`
a <-> b matches when b appears immediately after a. It is shorthand for a <1> b.
SELECT to_tsvector('english', 'The quick brown fox');
-- 'brown':3 'fox':4 'quick':2
SELECT to_tsvector('english', 'The quick brown fox')
@@ to_tsquery('english', 'quick <-> brown') AS adjacent; -- true
SELECT to_tsvector('english', 'The quick brown fox')
@@ to_tsquery('english', 'brown <-> quick') AS reversed; -- falseOrder matters. brown <-> quick asks for quick directly after brown, and the document has them the other way round.
Exact distance with `<N>`
a <N> b matches when b occurs exactly N positions after a.
SELECT to_tsvector('english', 'The quick brown fox')
@@ to_tsquery('english', 'quick <2> fox') AS two_apart; -- true
SELECT to_tsvector('english', 'The quick brown fox')
@@ to_tsquery('english', 'quick <-> fox') AS adjacent; -- falseOperator precedence
In a tsquery, ! binds tightest, then <->, then &, then |. So a & b <-> c means a & (b <-> c). Use parentheses when you mix operators.
| Operator | Meaning | Binds | Column |
|---|---|---|---|
| `!` | not | tightest | |
| `<->`, `<N>` | followed by, at distance N | next | |
| `&` | and | next | |
| `\ | ` | or | loosest |
Phrase queries from user input
You rarely write <-> by hand. Two constructors build it for you.
SELECT
phraseto_tsquery('english', 'full text search') AS phrase_query,
websearch_to_tsquery('english', '"full text" search') AS web_query;
-- phrase_query: 'full' <-> 'text' <-> 'search'
-- web_query: 'full' <-> 'text' & 'search'phraseto_tsquery treats the whole input as one phrase. websearch_to_tsquery creates a phrase only for the part inside double quotes. Other words are joined with &, as usual.
Here is a small end-to-end test:
CREATE TEMP TABLE notes (id int PRIMARY KEY, body text NOT NULL);
INSERT INTO notes VALUES
(1, 'Postgres full text search is fast'),
(2, 'Text search with full coverage'),
(3, 'Full, text search, step by step');
SELECT id
FROM notes
WHERE to_tsvector('english', body)
@@ phraseto_tsquery('english', 'full text search')
ORDER BY id;
-- 1
-- 3Row 2 contains all three lexemes but not in phrase order, so it is excluded. Row 3 matches even though commas separate the words, because punctuation does not take a position.
Stop words keep their place
Stop words are dropped from the tsvector, but they still use up a position. The phrase constructors account for this by leaving a gap.
SELECT to_tsvector('english', 'cat and dog');
-- 'cat':1 'dog':3
SELECT phraseto_tsquery('english', 'cat and dog');
-- 'cat' <2> 'dog'The query is <2> because the stop word and sits between the two terms. The phrase cat and dog therefore matches cat and dog but not cat or dog, where or is a different token in the same slot. It also does not match cat dog.
Approximating "within N words"
PostgreSQL has no built-in "within N" operator. Build one from an OR of exact distances. For "quick and fox within 3 words, in either order":
SELECT to_tsvector('english', 'The quick brown fox')
@@ to_tsquery('english',
'quick <-> fox | quick <2> fox | quick <3> fox |
fox <-> quick | fox <2> quick | fox <3> quick') AS near;
-- trueThis grows quickly with N. For larger windows, generate the expression in application code. A common alternative is to match with &, then use ts_rank_cd to push documents where the terms are close to the top.
SELECT id,
ts_rank_cd(to_tsvector('english', body),
to_tsquery('english', 'full & search')) AS cover_density
FROM notes
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'full & search')
ORDER BY cover_density DESC;ts_rank_cd uses cover density ranking, which scores a document higher when the matching lexemes are near each other. It needs the positions stored in the tsvector.
How positions flow through a phrase match
Edge cases and failure modes
- Stripped vectors.
strip(tsvector)removes positions to save space. A phrase query cannot match a stripped vector, andts_rank_cdhas nothing to measure. Do not strip a column you want to use for phrase search. - Position limit. Positions are capped at 16383. In very long documents, lexemes beyond that point share the maximum position, so phrase matching there is unreliable. Split very long documents into chunks if phrases deep in the text matter.
- Stemming. Phrases match stems, not exact words.
fox <-> jumpmatches "foxes jumped". It also matches "fox jumps", which may be more than you want. - Indexes. A GIN index on the
tsvectorcan serve phrase queries. The index treats<->like&to find candidate rows, and PostgreSQL then rechecks positions on the actual rows. The index narrows the search, but common words in a phrase can still produce many rechecks. - Negation.
!applies to a term or a phrase.a <-> !bmeansafollowed by anything that is notb, which is rarely what people intend. Prefera & !bwhen you only want to exclude documents containingb.
Exercise
A table column holds the text "Open source database engine". You run to_tsvector('english', body) @@ to_tsquery('english', 'source <2> engine'). Does it match? Then say what phraseto_tsquery('english', 'source of the database') produces, and why.
Show answer
Yes, it matches. "Open" is position 1, "source" is 2, "database" is 3 and "engine" is 4, so "engine" is exactly 2 positions after "source". The second query produces 'sourc' <3> 'databas'. The stop words "of" and "the" are not in the query, but they occupy positions 2 and 3, so the distance from "source" to "database" is 3. The lexemes shown are the English stems.