Sub topic 5
Matching documents with @@
This chapter assumes you can write basic SQL and have read the earlier chapters on tsvector and tsquery values. You should know that to_tsvector turns text into lexemes with positions and that to_tsquery builds a query from lexemes and operators. Here you will use the @@ operator that joins the two, and learn which forms of it use an index.
What @@ does
@@ is the text search match operator. It takes a document and a query and returns a boolean: true if the document satisfies the query, false otherwise. It does not score or order anything. Ranking comes in a later chapter.
SELECT to_tsvector('english', 'The foxes were running')
@@ to_tsquery('english', 'fox & run') AS matches;The result is true. Both sides were normalized with the english configuration, so foxes became fox and running became run. The stop words The and were were dropped from the document and played no part in the match.
The four forms of the operator
@@ accepts several operand combinations. Only the first two compare a tsvector with a tsquery directly.
| Form | Meaning |
|---|---|
| `tsvector @@ tsquery` | The standard form. |
| `tsquery @@ tsvector` | The same test with the operands swapped. |
| `text @@ tsquery` | Shorthand for `to_tsvector(text) @@ tsquery`. |
| `text @@ text` | Shorthand for `to_tsvector(text) @@ plainto_tsquery(text)`. |
The two text forms call to_tsvector without a configuration argument. They use the default_text_search_config setting, which depends on the server or database. The same query can therefore behave differently on two machines. Check your current value with:
SHOW default_text_search_config;The same query text can also behave differently from one session to the next:
SET default_text_search_config = 'english';
SELECT 'The foxes were running' @@ to_tsquery('fox & run') AS english_match;
SET default_text_search_config = 'simple';
SELECT 'The foxes were running' @@ to_tsquery('fox & run') AS simple_match;The first query returns true. The second returns false, because the simple configuration does not stem, so foxes stays foxes and never equals fox.
Matching against a table
Create a small table and search it. The document column is computed on the fly here. A later chapter moves it into a stored column.
CREATE TABLE notes (
id serial PRIMARY KEY,
body text NOT NULL
);
INSERT INTO notes (body) VALUES
('The quick brown fox jumped over the lazy dog'),
('Foxes are running through the forest'),
('A dog and a cat sat on the mat'),
('Quiet nights, no animals at all');
SELECT id, body
FROM notes
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'fox & !dog');Only row 2 is returned. Row 1 has fox but also dog, so !dog rejects it. Rows 3 and 4 have no fox.
Operators combine as you would expect. & requires both lexemes, | accepts either, ! excludes, and <-> requires adjacency. Parentheses group terms, so (fox | cat) & !dog is valid. Without parentheses, ! binds tightest, then <->, then &, then |.
What a match actually checks
A match depends on lexemes, not on the original strings.
- The document and the query must produce the same lexeme.
runningmatchesrunandrunsunderenglish, but not undersimple. - Word order and distance are ignored unless the query uses
<->.to_tsquery('english', 'dog & fox')matches a document wherefoxcomes beforedog. - Stop words are removed from both sides. A query consisting only of stop words becomes empty.
- Case is folded to lower case.
FOXandfoxare the same lexeme.
An empty query matches nothing. PostgreSQL also prints a notice when it builds one:
SELECT to_tsvector('english', 'The quick fox')
@@ to_tsquery('english', 'the') AS matches;This returns false, and the server reports NOTICE: text-search query contains only stop words or doesn't contain lexemes, ignored. If a search for a common word silently returns nothing, look for this notice first. The ts_debug function from the debugging chapter shows exactly what happened to each token.
NULL handling
@@ returns NULL if either operand is NULL. In a WHERE clause, a NULL result excludes the row, so a nullable column is skipped without an error. If you build a document from several columns, wrap each in coalesce. Otherwise one NULL column makes the whole concatenated document NULL:
SELECT to_tsvector('english', coalesce(NULL, '') || ' ' || 'fox') AS doc;Here the result is 'fox':1. Without coalesce, the || on text values would produce NULL, and the match would never succeed.
Indexes and the form you choose
The form of the left operand decides whether an index can help. A GIN index (covered in a later chapter) is built on an expression or a column, and the planner can use it only when your WHERE clause contains the same expression.
CREATE INDEX notes_body_fts_idx
ON notes USING gin (to_tsvector('english', body));
-- Can use notes_body_fts_idx: same expression, same configuration.
SELECT id FROM notes
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'fox');
-- Cannot use it: the configuration comes from a setting, not the expression.
SELECT id FROM notes
WHERE body @@ to_tsquery('fox');PostgreSQL only allows to_tsvector in an index expression when the configuration is given explicitly, because the one-argument version is not immutable. Writing to_tsvector('english', body) everywhere keeps your queries and index definitions consistent. On a table this small the planner may still choose a sequential scan. Check with EXPLAIN on realistic data volumes.
Common errors
- Mixing configurations. A document built with
simpleand a query built withenglishoften fail to match, because the lexemes differ. Use one configuration on both sides. - Syntax errors from raw input.
to_tsquery('english', 'fox dog')fails with a syntax error, because two words without an operator between them are invalid. For user input, useplainto_tsquery,phraseto_tsquery, orwebsearch_to_tsquery, as the next chapter explains. - Expecting substring matches.
to_tsquery('english', 'fo')does not matchfox. Prefix matching needs the:*suffix, as into_tsquery('english', 'fo:*'). - Expecting order.
@@filters rows. WithoutORDER BY, the result order is unspecified.
Exercise
A table has a column body, and an index was created with CREATE INDEX ON docs USING gin (to_tsvector('english', body)). A developer writes WHERE body @@ to_tsquery('english', 'index') and finds that the query is slow. Why, and how do you fix it?
Show answer
The text @@ tsquery form applies to_tsvector using default_text_search_config, so the planner does not see the indexed expression to_tsvector('english', body) and cannot use the GIN index. Rewrite the condition as WHERE to_tsvector('english', body) @@ to_tsquery('english', 'index'), which repeats the indexed expression exactly.
Exercise
What does SELECT to_tsvector('simple', 'Foxes run') @@ to_tsquery('english', 'fox') AS m; return, and why?
Show answer
It returns false. The simple configuration does not stem, so the document contains the lexeme foxes, while the english query looks for fox. The two lexemes differ, so there is no match.