to_tsvector
PG 8.3+→ tsvectorConverts a text document to a tsvector, normalizing words to their lexeme forms and removing stop words.
Signatures
to_tsvector ( document text ) → tsvectorto_tsvector ( config regconfig, document text ) → tsvectorParameters
| Parameter | Type | Description |
|---|---|---|
| config | regconfig | Text search configuration (e.g., 'english', 'simple'). Defaults to the server default configuration. |
| document | text | Text document to parse and normalize |
Examples
SELECT to_tsvector('english', 'The quick brown fox jumps over the lazy dog');'brown':3 'dog':9 'fox':4 'jump':5 'lazi':8 'quick':2SELECT to_tsvector('simple', 'Hello World');'hello':1 'world':2Calling `to_tsvector` inside a WHERE clause forces PostgreSQL to re-parse and normalize every row on every query, making full-table scans the only option. Store the vector in a generated column and index it instead.
✓ Instead: -- Bad: recomputed on every query SELECT * FROM articles WHERE to_tsvector('english', body) @@ plainto_tsquery('search'); -- Good: generated column + GIN index ALTER TABLE articles ADD COLUMN tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', coalesce(body,''))) STORED; CREATE INDEX articles_tsv_gin ON articles USING GIN(tsv); SELECT * FROM articles WHERE tsv @@ plainto_tsquery('english', 'search');
Pass the language explicitly: `to_tsvector('english', ...)`. The default config may not match your content language, leading to poor search quality. Use 'simple' to skip stemming for proper nouns or code.
ALTER TABLE articles ADD COLUMN search_vector tsvector GENERATED ALWAYS AS (to_tsvector('english', coalesce(title,'') || ' ' || coalesce(body,''))) STORED;Auto-maintained search vector column