Sub topic 9
Ranking Results with `ts_rank` and `ts_rank_cd`
Prerequisites: you should know basic SELECT, WHERE, and ORDER BY statements, and understand that PostgreSQL represents searchable text as tsvector and search input as tsquery.
A match only tells you whether a document satisfies a query. Ranking decides which matching documents appear first. PostgreSQL provides two main ranking functions:
ts_rankscores matches using term frequency and optional weights.ts_rank_cduses cover density. It favors documents where matching terms occur close together.
A rank is useful for ordering results, but it is not a probability or a universal relevance score. Compare scores only within the same query and ranking configuration.
Weight important fields
Weights let you make some matches more valuable than others. PostgreSQL supports four labels:
| Weight | Typical use | Default value |
|---|---|---|
| A | Title or name | 1.0 |
| B | Summary or main body | 0.4 |
| C | Metadata | 0.2 |
| D | Low-priority text | 0.1 |
The default values are used by the ranking functions. Apply weights when building the tsvector:
CREATE TEMP TABLE articles (
id integer PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
search tsvector NOT NULL
);
INSERT INTO articles (id, title, body, search)
VALUES
(1, 'PostgreSQL indexing',
'Learn how indexes speed up database searches.',
setweight(to_tsvector('english', 'PostgreSQL indexing'), 'A') ||
setweight(to_tsvector('english',
'Learn how indexes speed up database searches.'), 'B')),
(2, 'Database search guide',
'A practical introduction to PostgreSQL full-text search.',
setweight(to_tsvector('english', 'Database search guide'), 'A') ||
setweight(to_tsvector('english',
'A practical introduction to PostgreSQL full-text search.'), 'B'));
WITH q AS (
SELECT websearch_to_tsquery('english', 'PostgreSQL search') AS query
)
SELECT a.id,
a.title,
ts_rank(a.search, q.query) AS rank,
ts_rank_cd(a.search, q.query) AS cover_density_rank
FROM articles AS a
CROSS JOIN q
WHERE a.search @@ q.query
ORDER BY rank DESC;Choose the ranking function
ts_rank is a good general-purpose default. It rewards repeated matches and weighted fields. ts_rank_cd considers the distance between matching lexemes, so it can work better when a phrase-like concentration should rank highly.
Both functions accept a normalization option. For example, normalization value 32 scales the result into a smaller range:
SELECT ts_rank(a.search, q.query, 32) AS normalized_rank
FROM articles AS a
CROSS JOIN (
SELECT websearch_to_tsquery('english', 'PostgreSQL search') AS query
) AS q
WHERE a.search @@ q.query;Normalization can reduce the advantage held by very long documents. Test it with representative data because the best setting depends on your content.
Exercise
Which function should you try when matching terms that appear close together should receive a higher score?
Show answer
Try tsrankcd, then compare its ordering with ts_rank on representative documents.