AI Hints
Home›PostgreSQL Tutorial›Full-Text Search
PostgreSQL · Lesson 60 of 120

Ranking and Headlines

Best first, with snippets.

⏱ 2 min read▶ Video at 53:29🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A search should show the best matches first, with the matching words highlighted. Ts rank scores each match. Ts headline makes a snippet with the words marked.

  • Best first
  • ts_rank
  • ts_headline

Ranked, highlighted results

The CTE builds the query once. Ts rank scores each blurb, and we sort by it. Ts headline makes a short snippet, with matches in square brackets. Run it. Books about love or war, best matches first, with highlights.

query.sqlsql
WITH q AS (SELECT websearch_to_tsquery('english', 'love or war') AS query)
SELECT title,
       ts_headline('english', blurb, query, 'StartSel=[, StopSel=], MaxWords=10, MinWords=6') AS snippet
FROM books, q
WHERE to_tsvector('english', blurb) @@ query
ORDER BY ts_rank(to_tsvector('english', blurb), query) DESC
LIMIT 3;
Output
         title          |                   snippet
------------------------+----------------------------------------------
 Letters to Lisbon      | [love] story that crossed a [war]
 Stars Over Lagos       | stars and fall slowly, stubbornly in [love].
 Garden of Small Things | together, and a second chance at [love].
(3 rows)

Ranking tips

Setweight gives titles more weight than body text. Ts rank cd rewards words that appear close together. Normalisation options adjust for long documents. And ts headline is slow, so only run it on the top results.

keyvalue
setweighttitle > body
ts_rank_cdcloseness
Normaliselong docs
ts_headlinetop results only

Summary

Ts rank orders results by relevance, and ts headline shows snippets with highlights. Next, making search fast with a stored column and an index.

Key takeaways
  • ts_rank
  • ts_headline
  • Best first
Next up: A Search Column and Index — fast search