Sub topic 16
Debugging with `ts_debug`, `ts_stat`, and `EXPLAIN`
This chapter assumes basic SQL, PostgreSQL tables and indexes, and experience running queries in psql or another SQL client. You will learn how to find why a full-text search does not match and whether PostgreSQL uses its search index.
Inspecting parsing with `ts_debug`
PostgreSQL processes text in stages. A parser splits text into tokens, and dictionaries convert tokens into lexemes. A lexeme is the normalized term stored in a tsvector.
Use ts_debug to inspect these stages:
SELECT alias, token, dictionaries, dictionary, lexemes
FROM ts_debug('english', 'The foxes were running quickly');The result shows entries such as:
| token | lexemes | Meaning |
|---|---|---|
| foxes | `{fox}` | The stemmer reduced the plural form |
| were | `{}` | This stop word was discarded |
| running | `{run}` | The verb was stemmed |
If a search does not match, compare the configuration and input text used to create the document and the query. Searching an english vector with a simple query can produce different lexemes.
Finding common terms with `ts_stat`
ts_stat summarizes the vectors returned by a SQL query. It reports each lexeme, the number of documents containing it, and its total occurrence count.
SELECT word, ndoc, nentry
FROM ts_stat('SELECT search FROM articles')
ORDER BY ndoc DESC
LIMIT 20;Use ndoc to find very common terms. A term present in nearly every document usually provides little ranking value. Use nentry to see how often a term occurs overall.
ts_stat accepts a query string, so ensure that the query returns only the intended tsvector column. For a weighted vector, the weights remain available through the optional weight column when requested.
Checking plans with `EXPLAIN`
EXPLAIN displays the execution plan PostgreSQL chooses. For a full-text search, check whether the plan uses the GIN index instead of scanning every article.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, title
FROM articles
WHERE search @@ websearch_to_tsquery('english', 'database indexing')
ORDER BY ts_rank(search, websearch_to_tsquery('english', 'database indexing')) DESC
LIMIT 10;Look for an Index Scan or Bitmap Index Scan using articles_search_idx. A Seq Scan means PostgreSQL reads the table row by row. That can be correct for a small table or an unselective query. ANALYZE executes the statement, so do not use it on a write query unless you intend to perform that write.
Exercise
Which tool should you use first if running does not match a query for run?
Show answer
Use ts_debug with the same text-search configuration to check whether both forms become the same lexeme.