ts_headline Highlights Full-Text Matches

Build highlighted search snippets with ts_headline, websearch_to_tsquery, and custom StartSel and StopSel markers.

SqlData Fetching

Code

snippet
CREATE TABLE articles (
  id int PRIMARY KEY,
  title text NOT NULL,
  body text NOT NULL
);

INSERT INTO articles (id, title, body)
VALUES
  (1, 'Indexing Postgres', 'A Postgres index speeds up lookups. Choose the index type carefully.'),
  (2, 'Query Planning', 'The planner compares sequential scans with index scans.');

SELECT title,
       ts_headline(
         'english',
         body,
         websearch_to_tsquery('english', 'postgres index'),
         'StartSel=<mark>, StopSel=</mark>, MaxWords=18, MinWords=8'
       ) AS snippet
FROM articles
WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'postgres index');

-- Highlight every match instead of one fragment
SELECT ts_headline(
         'english',
         body,
         websearch_to_tsquery('english', 'index'),
         'HighlightAll=TRUE, StartSel=[, StopSel=]'
       ) AS full_highlight
FROM articles
WHERE id = 1;

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with articles among the objects involved.

The SQL constructs in play: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The articles table is the working surface here.

Statements that matter

SELECT title,
       ts_headline(
         'english',
         body,
         websearch_to_tsquery('english', 'postgres index'),
         'StartSel=<mark>, StopSel=</mark>, MaxWords=18, MinWords=8'
       ) AS snippet
FROM articles
WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'postgres index');
INSERT INTO articles (id, title, body)
VALUES
  (1, 'Indexing Postgres', 'A Postgres index speeds up lookups. Choose the index type carefully.'),
  (2, 'Query Planning', 'The planner compares sequential scans with index scans.');
SELECT ts_headline(
         'english',
         body,
         websearch_to_tsquery('english', 'index'),
         'HighlightAll=TRUE, StartSel=[, StopSel=]'
       ) AS full_highlight
FROM articles
WHERE id = 1;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`articles`.