Sub topic 10
Highlighting matches with ts_headline
This chapter assumes you have the articles table from the earlier chapters. That means a stored, weighted search column with a GIN index on it, and you know how @@ and ts_rank work. Basic SQL and psql are enough for everything else.
What ts_headline does
ts_headline takes the original text of a document and a tsquery. It returns an excerpt with the matching words wrapped in markers. Search result pages use it to show why a row matched.
ts_headline([config regconfig,] document text, query tsquery [, options text]) RETURNS textThe function does not read the stored tsvector. A tsvector keeps only lexemes and positions, not the original wording or punctuation. So ts_headline takes the raw text, parses it again with the given configuration, and marks the words whose lexemes appear in the query.
SELECT ts_headline(
'english',
'The quick brown foxes jumped over the lazy dogs',
to_tsquery('english', 'fox & dog'),
'StartSel=[[, StopSel=]], HighlightAll=true'
) AS snippet;
-- The quick brown [[foxes]] jumped over the lazy [[dogs]]The query contained fox and dog. The text contains foxes and dogs. Both reduce to the same lexemes under the english configuration, so both are highlighted.
Where it fits in a search query
Highlighting is the last step. It should only run for rows you will display.
Options
The fourth argument is a single string of comma-separated Name=Value pairs.
| Option | Default | Meaning |
|---|---|---|
| `StartSel` | `<b>` | Text inserted before each match |
| `StopSel` | `</b>` | Text inserted after each match |
| `MaxWords` | 35 | Longest excerpt, in words |
| `MinWords` | 15 | Shortest excerpt, in words |
| `ShortWord` | 3 | Words this short or shorter are dropped from the start and end of an excerpt |
| `HighlightAll` | false | Return the whole document, ignoring the length options |
| `MaxFragments` | 0 | Number of separate excerpts. 0 means one excerpt of the normal kind |
| `FragmentDelimiter` | ` ... ` | Text placed between fragments |
A value that contains spaces or commas must be wrapped in double quotes.
SELECT ts_headline(
'english',
a.body,
q.query,
'StartSel=[[, StopSel=]], MaxFragments=3, MaxWords=20, MinWords=8, FragmentDelimiter=" | "'
) AS snippet
FROM articles AS a,
websearch_to_tsquery('english', 'full text search') AS q(query)
WHERE a.search @@ q.query
LIMIT 5;With MaxFragments above 0, ts_headline picks up to that many short passages with dense matches. MaxWords and MinWords then apply to each fragment, not to the whole result. This suits long documents where one excerpt would miss most of the matches.
Highlighting only the displayed rows
Ranking and filtering use the indexed search column, which is fast. ts_headline is much slower because it parses the whole document text each time it runs. If you call it in the SELECT list of a query with ORDER BY, the planner may evaluate it for every matching row before the limit applies.
Do the filtering, ranking and limiting in a subquery. Call ts_headline outside it.
SELECT r.id,
r.title,
r.rank,
ts_headline('english', r.body, r.query,
'StartSel=[[, StopSel=]], MaxWords=35, MinWords=15') AS snippet
FROM (
SELECT a.id, a.title, a.body, q.query,
ts_rank(a.search, q.query) AS rank
FROM articles AS a,
websearch_to_tsquery('english', 'full text search') AS q(query)
WHERE a.search @@ q.query
ORDER BY rank DESC
LIMIT 10
) AS r
ORDER BY r.rank DESC;The inner query returns ten rows. The outer query runs ts_headline ten times. The outer ORDER BY is needed because a subquery does not guarantee that its order survives.
Edge cases and common errors
The configuration must match. ts_headline parses the text with the configuration you pass. If the tsvector was built with my_english (with unaccent) and you call ts_headline with english, a row can match in the WHERE clause and show no highlighted words. Pass the same configuration to both.
Matching rows can show no markers. A row can match because of its title while the snippet comes from the body. If no query term appears in the body, the result is the first MinWords to MaxWords words with no markers. This is expected. Highlight the title separately if you want to show a match there.
Negated terms are not highlighted. In fox & !dog, only fox is marked. A term the document must not contain has nothing to mark.
Phrase matches. For a phrase query, only words that form the phrase are highlighted. A stray occurrence of one word elsewhere may not be.
Output is not escaped. ts_headline inserts the markers into the text as it is. If body holds user-written content that contains markup, the markup stays in the snippet. If you show snippets in a web page, treat the result as untrusted. Escape the document before highlighting, or choose markers that cannot occur in the text and replace them after escaping.
Results change with the options. Snippet choice depends on MaxWords, MinWords and MaxFragments. Two calls with different options can pick different parts of the same document. Test with real documents.
Highlighting JSON documents
PostgreSQL also has ts_headline versions that accept json or jsonb. They highlight only string values and leave the structure and keys unchanged.
SELECT ts_headline(
'english',
'{"title": "Full text search", "tags": ["postgres", "search"]}'::jsonb,
to_tsquery('english', 'search'),
'StartSel=[[, StopSel=]]'
) AS doc;Summary of rules
- Use
ts_headlineon the original text, with the same configuration as thetsvector. - Run it after
LIMIT, in an outer query. - Use
MaxFragmentsfor long documents. - Escape or sanitize the output before showing it in a web page.
Exercise
A search page shows ten results. The query takes two seconds, and EXPLAIN (ANALYZE) shows that ts_headline ran for thousands of rows. What change fixes this, and why does it work?
Show answer
Move the filtering, ORDER BY and LIMIT 10 into a subquery, and call ts_headline in the outer query. ts_headline parses the full document text each time it runs, so it is expensive. In the new shape it runs only for the ten rows that are displayed. The WHERE a.search @@ query condition still uses the GIN index for the filtering.
Exercise
A row appears in the results, but its snippet has no highlighted words. Give two likely causes.
Show answer
First, the ts_headline configuration differs from the one used to build the stored tsvector, so the terms reduce to different lexemes. Second, the row matched through another field, such as the title, while the snippet was taken from the body, which has no query terms.