Sub topic 2
Text search configurations and the language setting
This chapter assumes you can write basic SQL in psql and have seen to_tsvector, to_tsquery and the @@ operator. It explains the argument that appeared first in each of those calls: the text search configuration. Choosing it correctly decides which words match, which rows can be indexed, and whether a multilingual table works at all.
What a configuration is
A text search configuration is a named recipe that turns raw text into lexemes. It has two parts:
- A parser that splits the text into tokens and labels each token with a type, such as
asciiword,word,numword,emailorurl. - A mapping from each token type to a list of dictionaries. For a given token, PostgreSQL asks the dictionaries in order. The first one that recognizes the token returns its lexemes, and the rest are skipped.
The english configuration maps word tokens to an English stop word list (so "the" is dropped) and then to the English Snowball stemmer (so "running" becomes run). The german configuration uses German stop words and stemming rules. The simple configuration lowercases tokens and keeps everything else unchanged.
The next chapters cover dictionaries in detail. Here the point is that one configuration name selects the entire pipeline.
Listing and inspecting configurations
Use \dF in psql, or query the catalog:
SELECT cfgname
FROM pg_ts_config
ORDER BY cfgname;A standard installation includes simple and one configuration per supported language, such as english, german, french, spanish and russian. The exact list depends on your PostgreSQL version. \dF+ english prints the token-type-to-dictionary mapping for one configuration.
Seeing the effect of the language setting
The same sentence produces different lexemes under different configurations:
SELECT to_tsvector('english', 'The running dogs');
SELECT to_tsvector('simple', 'The running dogs');The first query returns 'dog':3 'run':2. The second returns 'dogs':3 'running':2 'the':1. The English version drops "the" and stems the other two words. The simple version keeps all three.
A query must use a configuration that produces compatible lexemes. If the document and the query disagree, matching fails silently:
SELECT to_tsvector('english', 'foxes') @@ to_tsquery('simple', 'foxes') AS english_doc_simple_query,
to_tsvector('simple', 'foxes') @@ to_tsquery('english', 'foxes') AS simple_doc_english_query,
to_tsvector('english', 'foxes') @@ to_tsquery('english', 'foxes') AS same_config;The first two columns are false. The English document holds fox, but the simple query looks for foxes. The simple document holds foxes, but the English query looks for fox. Only the third column is true. PostgreSQL raises no error in the mismatched cases, so a wrong configuration shows up as missing results.
The default configuration
When you omit the configuration argument, PostgreSQL uses the default_text_search_config setting:
SHOW default_text_search_config;initdb sets this value from the server's locale, so a database created with a German locale may default to pg_catalog.german. You can change it per session, per role, or per database:
SET default_text_search_config = 'pg_catalog.english';
ALTER DATABASE mydb SET default_text_search_config = 'pg_catalog.english';The one-argument forms such as to_tsvector('some text') depend on this setting. That convenience has a cost, covered next.
Why indexes need an explicit configuration
An index expression or generated column must be immutable, meaning the same input always yields the same output. The two-argument to_tsvector(regconfig, text) is immutable. The one-argument to_tsvector(text) is only stable, because its result depends on a setting that can change. PostgreSQL rejects it in these places:
CREATE TABLE notes (
id bigserial PRIMARY KEY,
body text NOT NULL,
search tsvector GENERATED ALWAYS AS (to_tsvector(body)) STORED
);This fails with an error saying the generation expression is not immutable. Writing to_tsvector('english', body) fixes it.
There is a second reason to be explicit. If a query relies on the default and a session runs with a different default, the query uses different lexemes than the stored data and returns wrong results. Always pass the configuration name in application queries and in schema definitions.
The first argument has the type regconfig, which stores a reference to a configuration by its object ID. A string literal such as 'english' is converted to regconfig automatically. The conversion uses your search_path, so schema-qualify custom configurations if several schemas hold configurations with the same name.
Storing the language per row
Real data is often multilingual. Because regconfig is a column type, each row can carry its own configuration:
CREATE TABLE docs (
id bigserial PRIMARY KEY,
lang regconfig NOT NULL DEFAULT 'english',
body text NOT NULL,
search tsvector GENERATED ALWAYS AS (to_tsvector(lang, body)) STORED
);
INSERT INTO docs (lang, body) VALUES
('english', 'The foxes are running through the forest'),
('german', 'Die Füchse laufen durch den Wald'),
('simple', 'Foxes, Füchse, renards');The generation expression passes a column as the configuration. This is still immutable, because the value comes from the row and not from a session setting.
The query side needs a matching configuration. A single query string cannot be correct for every language, so filter by language and parse the query with that language:
SELECT id, body
FROM docs
WHERE lang = 'german'
AND search @@ plainto_tsquery('german', 'Fuchs');Without the lang filter, a German query could also test English rows, where it would match by accident or not at all. Applications usually know the user's language, or let the user pick one. If you must search every language at once, parse the query once per language and combine the results with OR, accepting the extra work.
Choosing a configuration
| Situation | Reasonable choice |
|---|---|
| Content is in one language | The matching language configuration |
| Content is multilingual, language known per row | A `regconfig` column, as above |
| Content is multilingual, language unknown | `simple`, or detect the language in the application |
| Names, product codes, identifiers | `simple`, because stemming would damage them |
| You need accent-insensitive search | A custom configuration (a later chapter) |
The trade-off with simple is recall. Searching for "run" will not find "running". The trade-off with a language configuration is precision on text that is not in that language. English stemming applied to a Spanish sentence produces some wrong lexemes, though exact word matches usually still work.
Common errors
- Changing the configuration but not the data. Stored tsvector values keep the lexemes created when they were built. If you switch a table from
englishtogerman, rebuild the stored column and the index. - Mismatched configurations between index and query. An expression index on
to_tsvector('english', body)is used only when the query repeatsto_tsvector('english', body)exactly. With a generated column this problem goes away, because queries reference the column. - Relying on the session default. Different clients and roles can have different defaults. Pass the name explicitly.
- Misspelled names. An unknown name raises
text search configuration "englsh" does not exist. That error is helpful, so do not wrap it in code that hides it.
When a search misbehaves, inspect the parsing directly:
SELECT alias, token, dictionaries, lexemes
FROM ts_debug('english', 'The foxes were running');The output shows each token, its type, the dictionaries consulted, and the final lexemes. A later chapter returns to this function.
Exercise
A table has the column search tsvector GENERATED ALWAYS AS (to_tsvector('english', body)) STORED. A developer runs SELECT * FROM t WHERE search @@ to_tsquery('simple', 'running') and gets no rows, although many bodies contain "running". Why, and what is the fix?
Show answer
The stored lexemes were built with the english configuration, so "running" is stored as run. The query uses simple, which looks for the literal lexeme running, so nothing matches and no error is raised. Parse the query with the same configuration as the column, for example to_tsquery('english', 'running').