Sub topic 11
Storing the tsvector in a generated column
This chapter assumes you can already build a tsvector with to_tsvector, apply setweight, and match with @@. You should also know how to create tables and indexes in PostgreSQL. Here we move the tsvector out of the query and into the table, so it is computed once at write time instead of on every search.
Why compute the tsvector at write time
The simplest search query calls to_tsvector on the column inside the WHERE clause:
SELECT id, title
FROM articles
WHERE to_tsvector('english', title || ' ' || body)
@@ websearch_to_tsquery('english', 'full text search');This works, but PostgreSQL must parse, normalize, and stem every row's text for every query. On a large table that cost dominates. You can index the expression instead, but a stored column has advantages:
- The parsing cost is paid once per write, not once per read.
- The weighted document (title as A, body as B) is defined in one place.
- Queries stay short and cannot drift from the index definition.
The alternatives are an expression index, a trigger that fills a plain tsvector column, or a generated column. The table below compares them.
| Approach | Extra storage | Keeps itself in sync | Notes |
|---|---|---|---|
| Expression index only | Index only | Yes | Query must repeat the exact expression. Cannot hold weights easily in a reusable form. |
| Trigger plus `tsvector` column | Column and index | Yes, if the trigger is correct | Works on any version. Needs trigger code to maintain. |
| Generated column (PostgreSQL 12+) | Column and index | Yes, enforced by the database | Declarative. The expression must be immutable. |
Defining the generated column
A generated column is computed from other columns in the same row. With STORED, PostgreSQL writes the result to disk when the row is inserted or updated.
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);Points to notice:
setweightlabels every lexeme from the title withAand every lexeme from the body withB. The||operator concatenates the two vectors and keeps the labels.coalesceprotects againstNULL. Concatenating aNULLtsvectorwith anything givesNULL, which would erase the whole document. Here both columns areNOT NULL, but the habit matters once a column becomes nullable.STOREDis required. PostgreSQL 12 supports only stored generated columns, not virtual ones.- The index on
searchis what makes@@fast. Indexing is covered in the next chapter, but the column is useless at scale without it.
The two-argument to_tsvector is mandatory
A generated column expression must be immutable, meaning the same input always gives the same output. The one-argument form to_tsvector(text) uses the session's default_text_search_config setting. That setting can change, so the function is only STABLE, and PostgreSQL rejects it:
-- Fails: generation expression is not immutable
ALTER TABLE articles
ADD COLUMN bad tsvector
GENERATED ALWAYS AS (to_tsvector(body)) STORED;The two-argument form to_tsvector('english', body) names the configuration explicitly and is immutable. The configuration name must be a constant. You cannot pass a per-row column as the configuration inside a generated column.
Inserting and querying
You never write to search. Inserts name only the source columns:
INSERT INTO articles (title, body) VALUES
('Full text search basics',
'PostgreSQL turns documents into lexemes and matches them with queries.'),
('Indexing',
'A GIN index makes text search fast on large tables.');
SELECT id, title, search FROM articles;The search value is a weighted vector such as 'basic':3A 'full':1A 'search':2A .... Each lexeme carries its position and its weight letter.
The query refers to the stored column directly:
SELECT a.id, a.title, ts_rank(a.search, q.query) AS rank
FROM articles AS a,
websearch_to_tsquery('english', 'text search') AS q(query)
WHERE a.search @@ q.query
ORDER BY rank DESC
LIMIT 10;Because the left side of @@ is the bare indexed column, the planner can use the GIN index.
How it behaves on write
Several behaviors follow from this design:
- You cannot assign a value to a generated column.
INSERT ... (search)andUPDATE ... SET search = ...both raise an error, except forDEFAULT. - On
UPDATE, PostgreSQL recomputes the column when the row is rewritten. Updating an unrelated column, such as a view counter, can still cost a recomputation in some versions, and it also writes a new row version. If those unrelated updates are frequent, keep volatile counters in a separate table. - Writes are slower than on a plain table, because of both the
to_tsvectorcall and the index maintenance. GIN index updates are especially costly for large documents, though GIN uses a pending list (fastupdate) to batch them. - The column adds storage. Long documents produce vectors that can be a large fraction of the original text size.
tsvectorvalues are compressed by TOAST when they are large.
Adding the column to an existing table
On a table that already holds data, ADD COLUMN ... GENERATED ... STORED rewrites the whole table while holding an ACCESS EXCLUSIVE lock. On a large production table this blocks reads and writes for the duration.
ALTER TABLE articles
ADD COLUMN search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')
) STORED;
CREATE INDEX CONCURRENTLY articles_search_idx ON articles USING gin (search);CREATE INDEX CONCURRENTLY avoids blocking writes during the index build, but the ALTER TABLE rewrite still locks the table. For a zero-downtime migration, add a plain tsvector column with a trigger, backfill it in batches, then index it.
Changing the definition
You cannot alter the expression of an existing generated column in PostgreSQL 12 to 16. Version 17 added ALTER COLUMN ... SET EXPRESSION. In older versions you drop the column and add it again, which rewrites the table. Plan weights and configuration before loading large amounts of data.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `generation expression is not immutable` | One-argument `to_tsvector`, or a non-constant configuration | Use `to_tsvector('english', ...)` |
| `cannot insert a non-DEFAULT value into column "search"` | Your insert or update names the generated column | Remove it from the column list |
| Rows never match | The vector is `NULL` because a source column was `NULL` and `coalesce` was missing | Wrap each source column in `coalesce` |
| Query ignores the index | You wrapped the column, for example `to_tsvector(search)`, or the query uses a different configuration | Compare the bare `search` column to a query built with the same configuration |
| Few matches for stemmed words | Query built with `'simple'` or another configuration than the stored vector | Use the same configuration in the query constructor |
The last two errors share a root cause: the configuration used to build the stored vector and the one used to build the tsquery must agree. A vector stemmed with english will not match a simple query for running, because the stored lexeme is run.
Exercise
A teammate writes search tsvector GENERATED ALWAYS AS (to_tsvector(title || ' ' || body)) STORED and PostgreSQL rejects it. Name the cause, fix the expression so that title words outrank body words, and explain what is still wrong if body later becomes nullable.
Show answer
The one-argument to_tsvector depends on default_text_search_config, so it is not immutable and cannot be used in a generated column. Fix it with setweight(to_tsvector('english', coalesce(title, '')), 'A') || setweight(to_tsvector('english', coalesce(body, '')), 'B'). Without coalesce, a NULL body would make the concatenation NULL, so the whole search value would be NULL and the row would never match any query.
Exercise
You must add a generated search column to a 200 GB production table that cannot be locked for long. Why is a plain ADD COLUMN ... GENERATED ... STORED risky, and what approach avoids the lock?
Show answer
It rewrites the entire table under an ACCESS EXCLUSIVE lock, blocking reads and writes. Instead add a nullable plain tsvector column, keep it current with a trigger on insert and update, backfill existing rows in small batches, and then build the GIN index with CREATE INDEX CONCURRENTLY.