Sub topic 2
Text Search Configurations and the Language Setting
This chapter assumes that you know basic SELECT and WHERE queries and can create PostgreSQL tables and indexes. You should also be able to run SQL in psql or another client.
What a text search configuration does
A text search configuration tells PostgreSQL how to interpret text. It combines:
- A parser, which breaks text into tokens such as words, numbers, and punctuation.
- Dictionaries, which normalize tokens, remove stop words, and apply stemming.
A configuration is associated with a language, but it does not detect the language automatically. The english configuration applies English rules. If you pass French text to it, PostgreSQL still applies English stemming and stop-word rules.
The built-in english configuration turns related words into the same lexeme. For example, running and runs may become a common stem. Words such as the are usually ignored.
SELECT
to_tsvector('english', 'The foxes were running quickly') AS document,
to_tsquery('english', 'run') AS query;The document and query should normally use the same configuration. Otherwise, one side might produce lexemes that the other side cannot match.
Inspecting and selecting configurations
PostgreSQL stores the default configuration in the default_text_search_config setting.
SHOW default_text_search_config;
SELECT cfgname, cfgnamespace::regnamespace AS schema_name
FROM pg_ts_config
ORDER BY schema_name, cfgname;The default can vary by installation. You can override it for one session:
SET default_text_search_config = 'pg_catalog.english';
SELECT to_tsvector('The foxes were running');However, an explicit name is clearer:
SELECT to_tsvector('english', 'The foxes were running');Common configurations include:
simple, which performs limited normalization without language-specific stemming.english, which uses English stop words and stemming.- Other language configurations, when the relevant PostgreSQL dictionaries are installed.
For multilingual data, choose a configuration based on the document's known language. You might store separate search vectors for different languages, or create a configuration that uses suitable dictionaries. Do not assume that one language configuration produces good results for every language.
Configuration consistency
A stored tsvector must be generated with the same rules used to build search queries. If you later change dictionaries or switch from simple to english, existing vectors may no longer represent the intended behavior. Rebuild stored vectors and review affected indexes after such a change.
Exercise
Why is to_tsvector('english', text) @@ to_tsquery('simple', query) usually a poor design?
Show answer
The two configurations can normalize words differently, so matching may fail or produce inconsistent results. Use the same explicit configuration on both sides.