Sub topic 8
Weighting title over body with setweight
This chapter assumes you can already build a tsvector with to_tsvector, build a tsquery, and match them with @@. It also assumes you have seen the articles table with a stored search column. Here you will make a title match count for more than a body match.
Why weights exist
A plain tsvector treats every lexeme the same. If you concatenate title and body into one string, a word in the title looks identical to a word buried in the third paragraph. Ranking then has nothing to separate "an article about indexing" from "an article that mentions indexing once".
PostgreSQL solves this by letting you label each lexeme position with one of four weights: A, B, C or D. A is the most important label. D is the default for any lexeme you have not labelled. The labels are stored inside the tsvector, and ts_rank reads them later.
Applying setweight
setweight(vector, weight) returns a copy of the vector in which every position carries the given label. The weight is a single "char" value, so it must be one of 'A', 'B', 'C' or 'D'.
SELECT setweight(to_tsvector('english', 'Fast search'), 'A') AS title_vec,
to_tsvector('english', 'Fast search') AS plain_vec;The first column prints each position with an A suffix, such as 'fast':1A. The second prints 'fast':1, which is the same as 'fast':1D because D is not shown.
To build a document from several fields, weight each field separately and join the results with ||.
SELECT setweight(to_tsvector('english', 'Fast search'), 'A') ||
setweight(to_tsvector('english', 'Search is fast when indexed'), 'B') AS doc;The || operator concatenates two tsvector values. It shifts the positions of the right-hand vector so they come after the left-hand ones. A lexeme that occurs in both fields keeps both entries, each with its own weight. That is the information the ranking functions need.
Weighting in a generated column
The stored column from the previous chapter already does this:
CREATE TABLE articles (
id bigserial PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')
) STORED
);
CREATE INDEX articles_search_idx ON articles USING gin (search);Three details matter here.
coalesceguards against NULL.NULL || tsvectorisNULL, so one missing field would erase the whole document. TheNOT NULLconstraints make it redundant in this table, but keep it when columns are nullable.- The configuration is explicit. Generated columns require immutable expressions. The two-argument form
to_tsvector('english', ...)is immutable. The one-argument form depends on a session setting and is rejected. - The labels are baked into stored data. Changing
'B'to'C'means changing the column expression. Before PostgreSQL 17 you must drop and re-add the column. PostgreSQL 17 and later hasALTER TABLE ... ALTER COLUMN ... SET EXPRESSION. Either way, every row is rewritten.
Seeing the effect on ranking
Insert two articles. In the first, the search term is only in the body. In the second, it is in the title.
INSERT INTO articles (title, body) VALUES
('Weekly notes',
'This week we looked at indexing, backups and replication.'),
('Indexing basics',
'A short introduction to how databases find rows quickly.');
SELECT a.title,
ts_rank(a.search, q.query) AS rank
FROM articles AS a,
to_tsquery('english', 'indexing') AS q(query)
WHERE a.search @@ q.query
ORDER BY rank DESC;Both rows match, because @@ ignores weights. The row whose title contains the word ranks first, because its lexeme carries the A label.
The default weight values
ts_rank multiplies each match by a number tied to its label. The defaults are:
| Label | Default value |
|---|---|
| A | 1.0 |
| B | 0.4 |
| C | 0.2 |
| D | 0.1 |
You can override them per query by passing a four-element real array. Note the order: it runs from D to A, which is the reverse of the label order.
SELECT a.title,
ts_rank('{0.1, 0.2, 0.4, 1.0}', a.search, q.query) AS default_rank,
ts_rank('{0.1, 0.2, 0.9, 1.0}', a.search, q.query) AS body_heavy_rank
FROM articles AS a,
to_tsquery('english', 'indexing') AS q(query)
WHERE a.search @@ q.query;The array is a query-time setting, so you can experiment with it without touching stored data. The values are relative. Each must be between 0 and 1, and only the proportions between them change the order.
Restricting a match to certain weights
A tsquery can require that a term was labelled with particular weights. Append a colon and the letters to the term.
SELECT title
FROM articles
WHERE search @@ to_tsquery('english', 'indexing:A');
SELECT title
FROM articles
WHERE search @@ to_tsquery('english', 'indexing:AB');The first query finds only rows where the term appears in the title. The second accepts either A or B. This is a filter, not a ranking hint: rows without a matching label are dropped.
Only to_tsquery accepts this syntax. websearch_to_tsquery, plainto_tsquery and phraseto_tsquery treat the colon as punctuation. That is one more reason to keep user input away from raw to_tsquery.
The GIN index stores the lexemes together with their label information, but it only narrows candidates. PostgreSQL rechecks the row to apply the weight restriction, which is cheap for a small candidate set.
Common mistakes
- Overwriting labels with a second
setweight.setweightreplaces every existing label in the vector. Applying'B'to a vector you already labelled'A'turns everything intoB. Weight each field first, then concatenate. - Reversing the array.
{1.0, 0.4, 0.2, 0.1}looks natural but meansDis the heaviest. The order is{D, C, B, A}. - Expecting weights to filter. A
B-only match still satisfies a plain@@. Weights change order, not membership, unless you add:A-style labels to the query. - Weighting by guesswork. Four levels is coarse. Use
Afor titles,Bfor summaries or headings,Cfor body text andDfor the rest. Then check real queries rather than tuning numbers blindly. - Assuming rank values are comparable across queries. A
ts_rankscore is only meaningful for ordering rows within one query.
Exercise
A table stores setweight(to_tsvector('english', title), 'A') || to_tsvector('english', body) in its search column. You want body matches to count nearly as much as title matches when ranking, without changing stored data. What do you change, and in what position of the weights array does the body's label go?
Show answer
Pass a custom weights array to ts_rank, such as ts_rank('{0.1, 0.2, 0.4, 0.9}', search, query). The body has no explicit label, so it carries D, which is the first element. To make it nearly equal to the title (A, the last element), write ts_rank('{0.9, 0.2, 0.4, 1.0}', search, query). Keeping the first value close to the last makes body matches nearly as heavy. Because the array is a query argument, no rows need rewriting.
Exercise
Why does setweight(setweight(to_tsvector('english', 'cats'), 'A'), 'C') not produce a vector with both A and C labels?
Show answer
setweight replaces all existing labels on every position of its input. The second call overwrites the A from the first, so the result carries only C. To mix labels, weight separate vectors and join them with ||.