Sub topic 9
Ranking results with ts_rank and ts_rank_cd
This chapter assumes you can already build a tsvector, write a tsquery, and match with @@. It also assumes you know how setweight labels lexemes with A to D. If any of that is unfamiliar, review those chapters first. The articles table with its weighted search column and GIN index is the same one defined earlier.
Why a match is not enough
@@ returns true or false. For a search box you also need an order, so the best hits come first. PostgreSQL ships two ranking functions that score a tsvector against a tsquery:
ts_rankscores by how often the query terms occur.ts_rank_cdscores by how close together the query terms occur. The "cd" stands for cover density.
Both return a real. A higher value means a better match. Both also take the lexeme weights (A to D) into account.
ts_rank: frequency
ts_rank rewards documents where the query lexemes appear more often.
SELECT label,
ts_rank(to_tsvector('english', doc),
to_tsquery('english', 'index')) AS rank
FROM (VALUES
('once', 'An index speeds up reads'),
('thrice','Index the table, then index the column, then check the index')
) AS d(label, doc)
ORDER BY rank DESC;The thrice row scores higher because the lexeme index appears three times in it. The function does not look at how the words relate to each other. For a query like postgres & search, it does not care whether the two words are adjacent or 500 words apart.
ts_rank_cd: proximity
ts_rank_cd looks for "covers", which are stretches of text that satisfy the whole query. Shorter covers score higher.
SELECT label,
ts_rank_cd(to_tsvector('english', doc),
to_tsquery('english', 'postgres & search')) AS rank
FROM (VALUES
('close', 'postgres full text search is fast'),
('far', 'postgres is a database and its tools include full text search')
) AS d(label, doc)
ORDER BY rank DESC;The close row wins because its two terms sit nearer each other.
ts_rank_cd needs the positions stored in the tsvector. A vector that has passed through strip() has no positions, and ts_rank_cd returns zero for it. If you strip vectors to save space, use ts_rank or keep the positions.
Neither function uses corpus-wide statistics such as inverse document frequency. A rare word and a common word count the same. The score reflects only the single document and the query.
Weights change the score
Each weight label carries a multiplier. The defaults, in the order D, C, B, A, are {0.1, 0.2, 0.4, 1.0}. A hit in an A-weighted lexeme (the title, in the articles table) counts ten times as much as a hit in D.
WITH docs(id, v) AS (
VALUES
(1, setweight(to_tsvector('english', 'Postgres tuning'), 'A')
|| setweight(to_tsvector('english', 'Notes on indexes'), 'B')),
(2, setweight(to_tsvector('english', 'Notes on indexes'), 'A')
|| setweight(to_tsvector('english', 'Postgres tuning'), 'B'))
)
SELECT id,
ts_rank(v, to_tsquery('english', 'postgres')) AS default_weights,
ts_rank('{0.1, 0.2, 0.4, 0.5}'::float4[], v,
to_tsquery('english', 'postgres')) AS flatter_weights
FROM docs
ORDER BY id;Document 1 has the term in its A part, so it outranks document 2 under the defaults. The optional first argument is a four-element float4[] that replaces the defaults. In the second column, lowering A to 0.5 shrinks the gap between the two documents. Pass this array when title matches should dominate more or less than the defaults allow.
Normalization: correcting for document length
Long documents contain more terms, so they tend to score higher. Both functions accept a last argument, an integer bit mask, that compensates for this. Combine flags by adding them or using |.
| Flag | Effect |
|---|---|
| 0 | Default. Ignores document length. |
| 1 | Divides the rank by 1 + the logarithm of the document length. |
| 2 | Divides the rank by the document length. |
| 4 | Divides by the mean harmonic distance between extents. Only `ts_rank_cd` implements it. |
| 8 | Divides by the number of unique words in the document. |
| 16 | Divides by 1 + the logarithm of the number of unique words. |
| 32 | Divides the rank by itself plus 1, which maps it into the range 0 to 1. |
Flag 1 is a common choice for articles of uneven length. Flag 32 is useful when you want a bounded number to show or compare, but it does not change the order of results from a single query.
SELECT a.id,
ts_rank_cd(a.search, q.query, 1 | 32) 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, a.id
LIMIT 10;Note a.id as a tie-breaker. Rank values often tie, and without a second sort key the order of tied rows can change between runs, which breaks pagination.
Where ranking sits in the query
The index helps with the WHERE clause only. Ranking is computed afterward, row by row, for every row that matched.
Two consequences follow:
- Always keep the
@@filter in theWHEREclause. A query that only hasORDER BY ts_rank(...)scores every row in the table. - A very common term can match hundreds of thousands of rows. The ranking function must read each matching row's
tsvectorto score it, and that vector is usually stored out of line. Ranking is therefore often the slowest part of a broad search, even with a perfect index. Check withEXPLAIN (ANALYZE)when a query that matches many rows is slow.
Common mistakes
- Comparing ranks across queries. A rank of 0.3 for one query and 0.3 for another do not mean equal quality. Use rank only to order the results of one query.
- Thresholding on the raw score. Filtering with
WHERE rank > 0.1breaks when you change weights, normalization, or the language configuration. Use@@to decide what matches and rank to order it. - Ranking with a different configuration than the one used to index. The query and vector must come from the same configuration, or lexemes will not line up.
- Expecting phrase order to matter in
ts_rank. Only<->in the query enforces order. Ranking does not. - Calling
ts_rank_cdon a stripped vector. The result is zero for every row.
Exercise
A search over articles returns 40,000 matching rows, and the page takes seconds even though the GIN index is used. Which part of the query is the likely cause, and what are two ways to reduce the cost?
Show answer
The cause is ranking. GIN narrows the rows with @@, but ts_rank or ts_rank_cd must then read and score every one of the 40,000 matching vectors before the sort and LIMIT. To reduce the cost, make the query more selective (for example, add other WHERE filters, or use websearch_to_tsquery so that terms combine with AND), or limit how many rows reach the ranking step, for example by filtering on a date range first. Another option is to cap the candidate set in a subquery and rank only that. Confirm the effect with EXPLAIN (ANALYZE).
Exercise
You want a hit in the title to count five times as much as a hit in the body, and you want long articles not to win just because they are long. Write the ORDER BY expression, assuming the title is weight A and the body is weight B.
Show answer
Set the weight array to {0.1, 0.2, 0.2, 1.0} and use flag 1 for length normalization: ORDER BY ts_rank('{0.1, 0.2, 0.2, 1.0}'::float4[], a.search, q.query, 1) DESC, a.id. Here B is 0.2 and A is 1.0, so a title hit counts five times a body hit.