Sub topic 4
Queries as tsquery: &, |, ! and <->
A tsquery is the query half of PostgreSQL full-text search. It stores search terms as normalized lexemes and joins them with operators. This chapter assumes you know the tsvector type from the previous chapters and can run queries in psql. You should also know that a text search configuration controls how text is split and normalized.
What a tsquery contains
A tsquery holds lexemes and operators, not raw words. The @@ operator compares it against the lexemes in a tsvector, so a query term only matches if it was normalized the same way as the document.
SELECT to_tsquery('english', 'foxes & jumped');
-- 'fox' & 'jump'
SELECT 'foxes & jumped'::tsquery;
-- 'foxes' & 'jumped'to_tsquery runs each term through the configuration, so foxes becomes fox and jumped becomes jump. A plain cast to tsquery does no normalization. It keeps the words as typed, and a query built this way will usually fail to match a stemmed document.
The four operators
| Operator | Meaning | Example | Matches a document that... | Column | Column |
|---|---|---|---|---|---|
| `&` | AND | `fox & dog` | contains both lexemes | ||
| `\ | ` | OR | `fox \ | dog` | contains at least one |
| `!` | NOT | `!cat` | does not contain the lexeme | ||
| `<->` | FOLLOWED BY | `quick <-> fox` | has `fox` immediately after `quick` |
The operators use the following precedence, from tightest to loosest binding:
!<->&|
Parentheses override this order.
SELECT to_tsquery('simple', 'a | b & c');
-- 'a' | 'b' & 'c' (means a OR (b AND c))
SELECT to_tsquery('simple', '(a | b) & c');
-- ( 'a' | 'b' ) & 'c'
SELECT to_tsquery('simple', '!a & b');
-- !'a' & 'b' (means (NOT a) AND b)The tree below shows how fox & (jump | run) & !dog is structured. ! applies only to dog, and the parentheses group the OR.
Matching with the operators
The @@ operator returns true when the document satisfies the whole expression.
SELECT
to_tsvector('english', 'The quick brown fox jumps over the lazy dog') AS doc
\gset
SELECT
:'doc'::tsvector @@ to_tsquery('english', 'fox & dog') AS both,
:'doc'::tsvector @@ to_tsquery('english', 'cat | dog') AS either,
:'doc'::tsvector @@ to_tsquery('english', 'fox & !cat') AS fox_no_cat,
:'doc'::tsvector @@ to_tsquery('english', 'fox & !dog') AS fox_no_dog;The \gset line is a psql feature that stores the result in a variable named doc. The four results are true, true, true and false.
Phrase operators and distance
<-> compares lexeme positions in the tsvector. It matches only when the right-hand lexeme is exactly one position after the left-hand one. <N> allows a specific distance of N positions.
SELECT
to_tsvector('english', 'quick brown fox') @@ to_tsquery('english', 'quick <-> fox') AS adjacent,
to_tsvector('english', 'quick brown fox') @@ to_tsquery('english', 'quick <2> fox') AS two_apart,
to_tsvector('english', 'quick brown fox') @@ to_tsquery('english', 'brown <-> fox') AS next_to;The results are false, true and true. The <-> operator is the same as <1>. Because the match depends on positions, a tsvector built with strip() has no positions, and phrase queries against it never match.
Stop words still occupy a position when the document is converted, so the quick fox has quick at position 2 and fox at position 3. Text that appears between the two words in the document therefore changes the distance you must ask for.
Prefix matching and weight filters
A lexeme can carry a suffix after a colon.
:*turns it into a prefix match.:A,:B,:Cor:Drestricts it to lexemes carrying that weight. Weights are covered in a later chapter.
SELECT to_tsvector('english', 'supernovae and supernatural events')
@@ to_tsquery('english', 'supern:*') AS prefix_match;
-- true
SELECT to_tsquery('english', 'fox:AB & dog:*');
-- 'fox':AB & 'dog':*A prefix is still stemmed before it is compared, so a short prefix can turn into something unexpected. Check unusual prefixes with a query like the one above before you rely on them.
Combining and inspecting tsquery values
You can build queries in code instead of as one string. The operators &&, || and !! combine existing tsquery values, and tsquery_phrase joins two queries with a distance.
SELECT
to_tsquery('english', 'fox') && to_tsquery('english', 'dog') AS anded,
to_tsquery('english', 'fox') || to_tsquery('english', 'dog') AS ored,
!! to_tsquery('english', 'fox') AS negated,
tsquery_phrase(to_tsquery('english', 'quick'),
to_tsquery('english', 'fox'), 2) AS phrase;This is how an application adds a mandatory filter term to a user's query without rewriting the string. It also avoids building a query string by concatenation.
Common errors and gotchas
Syntax errors on plain input. to_tsquery expects operators between terms and does not accept free text.
SELECT to_tsquery('english', 'quick fox');
-- ERROR: syntax error in tsquery: "quick fox"User input such as quick fox or rock & roll! can raise this error. The next chapter covers the constructors that accept arbitrary text.
Stop words disappear, and so can the whole query. A stop word is removed from the query along with the operator that joined it.
SELECT to_tsquery('english', 'the & fox');
-- 'fox'
SELECT to_tsquery('english', 'the | a');
-- NOTICE: text-search query contains only stop words or doesn't contain lexemes, ignored
-- (returns an empty query)An empty query matches nothing, so a search for only stop words returns no rows instead of every row.
Negation alone is expensive. !cat matches every document that lacks cat, which is usually most of the table. A GIN index cannot narrow that down, so the planner may scan the table. Pair a negated term with at least one positive term, as in fox & !cat.
Operators inside terms. A term that contains punctuation must be quoted, as in to_tsquery('english', '''rock & roll'''). Quoted text is parsed as one term, which the configuration may then split into several lexemes joined by <->. If the quoting is wrong, the result is a syntax error, not a silent change in meaning.
Exercise
Write a query that is true for a document containing "postgres" and either "index" or "search", but not "mysql". Which operators need parentheses, and why?
Show answer
to_tsquery('english', 'postgres & (index | search) & !mysql'). The parentheses are needed around index | search because & binds tighter than |. Without them the query would mean (postgres & index) | (search & !mysql). The ! needs no parentheses because it binds tightest and applies only to mysql.
Exercise
The document text is 'quick brown fox'. Does to_tsvector('english', 'quick brown fox') @@ to_tsquery('english', 'quick <-> fox') return true? What single change makes it true?
Show answer
It returns false, because quick is at position 1 and fox is at position 3, so they are two positions apart. Change the operator to <2>, or use quick <-> brown <-> fox, and the query matches.