skip to content

For a PostgreSQL 18 help-centre search, how do you store a weighted tsvector, then rank with ts_rank_cd and highlight with ts_headline without slowing every query?

level: seniorimportance: should knowfreq 41%

answer

  1. labels A to D
  2. STORED, not 18's default
  3. ranking reads every match
  4. headline re-parses the original
  5. rank first, highlight the page

basics

~10 s

Concatenate setweight(to_tsvector('english', title), 'A') with lower-weighted summary and body in a generated column marked STORED, since 18's default VIRTUAL cannot be indexed. Rank matches with ts_rank_cd, then call ts_headline only on the final page.

solid answer

~40 s

`setweight` labels positions `A`, `B`, `C` or `D` (`D` is the default), and the labels survive `||`, so title, summary and body can feed one `tsvector`. Declare it `GENERATED ALWAYS AS (...) STORED`: on PostgreSQL 18 a generated column without `STORED` is virtual, and `indexes on virtual generated columns are not supported`. `ts_rank` scores lexeme frequency; `ts_rank_cd` adds proximity (cover density) and needs positions, returning 0 on a `strip()`ped vector. Both use default weights `{0.1, 0.2, 0.4, 1.0}` for D, C, B, A and an optional normalization bitmask for document length. Ranking must read the `tsvector` of every matching row, so common terms are costly. `ts_headline` re-parses the original text, so rank and `LIMIT` in a subquery and highlight only those rows, sanitising its output against XSS.

code

sql · 7 lines
sql
ALTER TABLE help_article
  ADD COLUMN search_tsv tsvector
  GENERATED ALWAYS AS (
       setweight(to_tsvector('english', coalesce(title, '')),   'A')
    || setweight(to_tsvector('english', coalesce(summary, '')), 'B')
    || setweight(to_tsvector('english', coalesce(body, '')),    'D')
  ) STORED;

go deeper

for a junior

Know that setweight labels parts of a document A to D and that ts_rank orders matches by relevance.

for a middle

Explain building one weighted tsvector with || and coalesce, the default weights, the normalization flags and the difference between ts_rank and ts_rank_cd.

for a senior

Show the cost model: ranking reads every match, ts_headline re-parses originals, so rank in a subquery and highlight the page. Remember STORED on 18 and sanitise headline output.

for a principal

Decide how much relevance tuning the product needs; when field weights and length normalization are not enough, that is a signal toward corpus-aware ranking outside the database.

## The help-centre shape A vendor's `help_article` table has `title`, `summary` and `body`. A hit in the title should outrank a hit buried in the body, results should come back best-first, and each result should show a snippet with the matched words highlighted. PostgreSQL covers all three with `setweight`, the ranking functions and `ts_headline`, provided you know what each costs. ## Storing a weighted tsvector `setweight(vector, label)` stamps every position of a `tsvector` with a **weight label**: `A`, `B`, `C` or `D`. `D` is the default and is not displayed. Labels survive concatenation with `||`, which also shifts the right-hand positions after the left-hand ones, so one `tsvector` can carry the whole article: - title words labelled `A`; - summary words labelled `B`; - body words labelled `D`; - each part wrapped in `coalesce(..., '')`, because a `NULL` part would make the whole concatenation `NULL`. Keep it in a **stored generated column** so it is computed on write and can be indexed. The expression must be **immutable**, which is why every `to_tsvector` call names its configuration: the one-argument form depends on `default_text_search_config` and is only `STABLE`. **PostgreSQL 18 changed the default kind of generated column.** Before 18, every generated column was stored. In 18, `GENERATED ALWAYS AS (...)` without a keyword creates a **virtual** column, computed on read, and creating an index on it fails with `indexes on virtual generated columns are not supported`. Write `STORED` explicitly. Adding the column rewrites the table, which is a schema-change concern, and the GIN index on it belongs to the GIN and GiST index material. ## Ranking: ts_rank and ts_rank_cd | | `ts_rank` | `ts_rank_cd` | |---|---|---| | Scores | how often the query's lexemes occur | the same, plus how close together the matches are (cover density) | | Needs positions | no | yes: lexemes stripped by `strip()` are ignored, and a fully stripped vector ranks 0 | | Weights argument | `{D, C, B, A}`, default `{0.1, 0.2, 0.4, 1.0}` | the same | | Normalization | bitmask | the same, plus flag 4 (mean harmonic distance between extents) | The **normalization** integer is a bitmask, applied in flag order: `0` ignores length (the default), `1` divides by 1 + the log of the document length, `2` by the length, `8` by the number of unique words, `16` by 1 + its log, and `32` maps the rank into 0 to 1 as `rank / (rank + 1)`. Flag 32 is cosmetic and does not change the order. To make titles count even more, pass your own array, for example `'{0.05, 0.2, 0.5, 1.0}'`. A query can also be restricted to a label: `to_tsquery('english', 'password:A')` matches only title words. ## What ranking costs An index answers *which rows match*; it does not return them in relevance order. To sort by `ts_rank_cd`, PostgreSQL must: 1. fetch every matching row's `tsvector` from the table (detoasting it if it is large); 2. compute the rank for each one; 3. sort them all to keep the top N. A rare term matching 40 articles costs nothing. A common term matching most of the help centre makes every page-one query rank the whole corpus; the manual calls ranking expensive for exactly this reason. Mitigations: filter first (product, language, published flag), require all words rather than any, and cap the candidate set before ranking when approximate order is acceptable. ## Highlighting with ts_headline `ts_headline(config, document, query, options)` returns an excerpt with query words wrapped in markers. It works on the **original text**, not the `tsvector`, so it re-parses each document it is given and is slow. Useful options: `MaxWords` and `MinWords` (defaults 35 and 15), `ShortWord` (3), `MaxFragments` (0 means a single excerpt; above 0 selects fragment mode), `StartSel` and `StopSel` (defaults `<b>` and `</b>`), and `FragmentDelimiter` (default ` ... `). Two rules follow: - **Highlight only the page you return.** Rank and `LIMIT` in a subquery, then call `ts_headline` in the outer query, so it runs ten times rather than once per match. The planner already tries to postpone expensive select-list expressions past a sort with `LIMIT`; the subquery makes that guarantee explicit. - **Do not trust the output as HTML.** The manual warns that `ts_headline` does not reliably remove markup; strip HTML from the input or sanitise the output before rendering it.

  • Why call ts_headline in an outer query instead of next to ts_rank_cd?
    `ts_headline` re-parses the full original text of each row it receives. Ranking and `LIMIT` inside a subquery guarantee it runs only for the page returned, not for every match. The planner already tries to defer expensive select-list expressions past a sort with `LIMIT`, but the subquery makes the cost independent of that optimisation.
  • How do you make a title hit outrank a body hit, and also offer a title-only search?
    Label title positions `A` and body positions `D` with `setweight`, then rank with the default `{0.1, 0.2, 0.4, 1.0}` weights or a steeper custom array. For title-only search, restrict the query lexeme to the label, as in `to_tsquery('english', 'password:A')`, which matches only `A`-labelled positions.
  • A common word makes page-one queries slow even with an index; why, and what helps?
    The index finds the matching rows, but ranking must read and score every match's `tsvector` and sort them all before `LIMIT` applies. Narrow the candidates first (product, language, published), require all terms, or rank a capped candidate set when approximate order is acceptable.

  • An index returns full-text matches already ordered by ts_rank.
  • Normalization flag 32 changes which articles rank first.
  • ts_headline reads the stored tsvector, so calling it on every match is cheap.
  • ts_rank_cd works fine on a strip()ped tsvector and saves space.
  • On PostgreSQL 18, GENERATED ALWAYS AS without a keyword still creates a stored column.
  • ts_headline output is safe to insert into HTML because it strips tags.

Assumes PostgreSQL 18, where GENERATED ALWAYS AS without STORED creates a virtual column that cannot be indexed; before 18 every generated column was stored.