Sub topic 16
Debugging with ts_debug, ts_stat and EXPLAIN
This chapter assumes you can write a basic full-text query with to_tsvector, to_tsquery and @@. It also assumes you know what a stored tsvector column and a GIN index are. Most full-text search problems fall into three groups: a term that does not match, a corpus with unexpected vocabulary, and a query that is slow. PostgreSQL has one tool for each group. ts_debug explains how text is parsed. ts_stat summarizes the lexemes in a column. EXPLAIN shows whether the index is used.
Start from the symptom
Inspecting parsing with ts_debug
ts_debug runs the parser and the dictionaries on a string and reports each step. Use it when a document should match but does not.
SELECT alias, token, dictionaries, lexemes
FROM ts_debug('english', 'The foxes were running');Each row is one token from the parser. The columns mean the following:
| Column | Meaning |
|---|---|
| `alias` | The token type, such as `asciiword`, `numword`, `email`, `url` or `blank` |
| `token` | The text the parser extracted |
| `dictionaries` | The dictionaries the configuration consults for this token type, in order |
| `lexemes` | What the dictionary chain produced |
For the input above, The and were come back with an empty lexemes array {}. They are stop words, so the english_stem dictionary discards them. foxes becomes {fox} and running becomes {run}. The spaces appear as blank tokens with no lexemes.
An empty lexemes array means the token is dropped, not that it failed. This is the usual reason a search for a common word returns nothing. If you search for the, the query becomes empty.
SELECT to_tsquery('english', 'the');PostgreSQL emits a notice that the query contains only stop words, and the result is an empty tsquery. Matching against an empty query returns no rows.
Run ts_debug on both sides of a failed match. Compare the lexemes of the document with the lexemes of the query. If they differ, the configurations or inputs differ.
Token types that surprise people
The parser classifies text before any dictionary runs. A string like postgres-16 may be split into a hyphenated word plus its parts. An address like [email protected] is a single email token, so searching for example will not match it. Use ts_debug on realistic data, not only on clean sentences. It will show you which token type is responsible.
Testing one dictionary with ts_lexize
ts_lexize calls a single dictionary and skips the parser.
SELECT ts_lexize('english_stem', 'stars') AS stemmed,
ts_lexize('english_stem', 'the') AS stop_word;The first result is {star}. The second is an empty array, because the is a stop word. A NULL result means the dictionary does not recognize the word, so the next dictionary in the chain gets a turn. This distinction matters when you build a chain such as unaccent, english_stem.
Finding vocabulary problems with ts_stat
ts_stat takes a query that returns a tsvector column and reports statistics for every lexeme. The query is passed as a string.
SELECT word, ndoc, nentry
FROM ts_stat('SELECT search FROM articles')
ORDER BY ndoc DESC, nentry DESC, word
LIMIT 20;ndoc is the number of documents containing the lexeme. nentry is the total number of occurrences. Three uses are common:
- Find noise. Lexemes with a very high
ndocappear in almost every row. They add index size and little selectivity. Consider adding them to a custom stop word list. - Find junk. Long hex strings, tokens from markup, or file paths often show up with
ndoc = 1. They indicate dirty input or an unexpected token type. - Confirm a term exists. If a lexeme is missing from the output, no document contains it, whatever the original text looked like.
ts_stat reads the whole table. Run it on a replica or on a sample, for example SELECT search FROM articles TABLESAMPLE SYSTEM (5), rather than on a busy production table at peak.
Checking the plan with EXPLAIN
A correct query can still be slow. Run the exact query under EXPLAIN (ANALYZE, BUFFERS).
EXPLAIN (ANALYZE, BUFFERS)
SELECT a.id, a.title
FROM articles AS a
WHERE a.search @@ websearch_to_tsquery('english', 'full text search')
ORDER BY ts_rank(a.search, websearch_to_tsquery('english', 'full text search')) DESC
LIMIT 10;On a table with many rows, a healthy plan has this shape:
Limit
-> Sort
-> Bitmap Heap Scan on articles a
Recheck Cond: (search @@ '...'::tsquery)
-> Bitmap Index Scan on articles_search_idx
Index Cond: (search @@ '...'::tsquery)A Seq Scan on a large table means the index is not used. Check these causes in order:
- The column is not the one indexed. The
@@must compare against the indexedtsvectorcolumn or the exact indexed expression. An expression such asto_tsvector('english', body) @@ ...only uses an expression index built on that same expression. - The one-argument form.
to_tsvector(body)depends ondefault_text_search_config. It is not immutable, so it cannot be used in an index expression. Always pass the configuration name explicitly. - Stale statistics. Run
ANALYZE articles;after a bulk load, so the planner estimates how many rows match. - A small table. On a few hundred rows, a sequential scan is faster, and the planner is right to choose it.
To check that the index is usable at all, disable sequential scans in your session for the test only:
SET enable_seqscan = off;Run the EXPLAIN again, then RESET enable_seqscan;. If the plan now uses the GIN index, the index works and the planner prefers a scan for cost reasons. If it still does not, the query does not match the indexed expression.
Cost that the index does not remove
The GIN index narrows the rows, but later steps still work on every matching row. ts_rank must read each matching tsvector to compute a score, so a query that matches 500,000 rows ranks 500,000 rows before LIMIT applies. In EXPLAIN ANALYZE, look for a large Sort node and for high Heap Blocks counts. Reduce the cost by making queries more selective, for example with an additional filter on date or category.
ts_headline is more expensive still, because it reparses the original text. Apply it only to the final rows, using a subquery:
SELECT id, ts_headline('english', body, q.query) AS snippet
FROM (
SELECT a.id, a.body
FROM articles AS a,
websearch_to_tsquery('english', 'full text search') AS q(query)
WHERE a.search @@ q.query
ORDER BY ts_rank(a.search, q.query) DESC
LIMIT 10
) AS top, websearch_to_tsquery('english', 'full text search') AS q(query);The inner query picks ten rows. Only those ten pass through ts_headline.
A debugging checklist
- Run
ts_debugon the document text and on the query term. Compare the lexemes. - If lexemes are empty, find the stop word or token type responsible.
- If lexemes differ, compare the configuration names used when storing and when querying.
- Run
ts_statto check whether the lexeme exists in the corpus and to find noisy terms. - Run
EXPLAIN (ANALYZE, BUFFERS)and look forBitmap Index Scanon the GIN index. - If the plan is slow despite the index, check how many rows match and how many are ranked.
Exercise
A search for running returns nothing, although a row contains "She was running home". The search column was filled with to_tsvector('simple', body). The query is websearch_to_tsquery('english', 'running'). Which tool shows the cause, and what does it show?
Show answer
Use ts_debug (or simply to_tsvector and websearch_to_tsquery output) on both sides. The stored document has the lexeme running because the simple configuration does not stem. The query is built with english, which stems it to run. The lexemes run and running do not match. The fix is to use the same configuration for the stored column and the query.
Exercise
EXPLAIN on a table with two million rows shows a Seq Scan for WHERE to_tsvector('english', body) @@ q, although a GIN index exists on the search column. Why, and how do you fix it?
Show answer
The query evaluates an expression on body, but the index is on the search column. The planner can only use an index when the query matches the indexed column or expression. Rewrite the condition as WHERE search @@ q, or create an expression index on to_tsvector('english', body).