Sub topic 15
Building a custom configuration with unaccent
This chapter assumes you can run SQL in psql, know what a tsvector and a tsquery are, and have read the chapters on text search configurations and dictionaries. It also assumes you have the articles table with a generated search column and a GIN index.
The problem: accents split your matches
The built-in english configuration does not remove accents. A user who types cafe will not find a document that says café, and the reverse is also true. The two spellings produce different lexemes.
SELECT to_tsvector('english', 'Café résumé');The lexemes keep their accents, so a query for cafe or resume matches nothing in this document. Names, loanwords, and multilingual content all cause this. Most users type without accents, because they are faster to type and often unavailable on a phone keyboard.
The fix is to normalize accents during parsing. Both the stored document and the incoming query must go through the same normalization. A custom text search configuration is the way to do that.
How the pipeline works
A configuration maps each token type produced by the parser to a list of dictionaries. PostgreSQL tries the dictionaries in order. Most dictionaries either produce lexemes or reject the token. The unaccent dictionary is a filtering dictionary. It strips the accents and passes the result to the next dictionary in the list.
Order matters. If english_stem came first, it would accept the token and the chain would stop there, so unaccent would never run. Always put unaccent before the stemmer.
Creating the configuration
You cannot edit the built-in configurations. Instead, copy one and change the mapping on your copy. You need the unaccent extension first, which ships in PostgreSQL's contrib modules.
CREATE EXTENSION IF NOT EXISTS unaccent;
CREATE TEXT SEARCH CONFIGURATION my_english (COPY = english);
ALTER TEXT SEARCH CONFIGURATION my_english
ALTER MAPPING FOR hword, hword_part, word
WITH unaccent, english_stem;
SELECT to_tsvector('my_english', 'Café résumé');The result is 'cafe':1 'resum':2. The accents are gone, and the stemmer has reduced resume to resum.
The three token types in the mapping are the ones that carry words: word is a plain word, hword is a hyphenated compound, and hword_part is one piece of a compound. Other token types such as numbers and URLs keep their original mappings from the english copy.
Queries must use the same configuration:
SELECT to_tsvector('my_english', 'Café résumé')
@@ websearch_to_tsquery('my_english', 'cafe resume') AS matches;This returns true. A query written with accents, such as café, also matches, because the query goes through the same unaccent step.
Checking the result with ts_debug
Use ts_debug to confirm that the mapping does what you intended.
SELECT alias, token, dictionaries, lexemes
FROM ts_debug('my_english', 'Café résumé');For each word token, the dictionaries column should list unaccent followed by english_stem, and lexemes should show the unaccented stem. If you only see english_stem, the ALTER MAPPING did not apply to that token type. Run the same query against english to compare.
Using the configuration in a generated column
Replace 'english' with 'my_english' in the generated column. The two-argument form to_tsvector(regconfig, text) is immutable, so PostgreSQL accepts it in a generated column as long as the configuration is a constant, as it is here.
A generated column's expression is fixed once it is created, so you cannot swap the configuration in place. On older versions, drop and re-add the column. This rewrites the table, and it drops the dependent index too:
ALTER TABLE articles DROP COLUMN search;
ALTER TABLE articles ADD COLUMN search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('my_english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('my_english', coalesce(body, '')), 'B')
) STORED;
CREATE INDEX articles_search_idx ON articles USING gin (search);PostgreSQL 17 and later offer ALTER COLUMN ... SET EXPRESSION, which changes the expression in place. It still rewrites the table, so plan for the lock and the time on large tables.
Then query with the same configuration:
SELECT a.id, a.title, ts_rank(a.search, q.query) AS rank
FROM articles AS a,
websearch_to_tsquery('my_english', 'café') AS q(query)
WHERE a.search @@ q.query
ORDER BY rank DESC
LIMIT 10;The @@ filter still uses the GIN index. Accent removal happens when the lexemes are built, not when the query runs.
Common errors and gotchas
- Changing the configuration does not update stored data. If you run
ALTER MAPPINGon a configuration that a stored column already uses, existingtsvectorvalues keep the old lexemes. Rebuild the column, or the stored values and new queries will disagree. For this reason, treat a configuration used by an index as frozen. Create a new one, such asmy_english_v2, and migrate to it. - Name resolution depends on
search_path. A bare'my_english'is resolved at the time the expression is parsed. Schema-qualify the name, for examplepublic.my_english, in code that runs under different roles or search paths. - Dump and restore. The configuration is a database object, so it is part of
pg_dump. Theunaccentextension must exist in the target database before the restore reaches objects that use it. - The stemmer still sets the language.
unaccentremoves diacritics and nothing else. Stemming for French text needsfrench_stem, so a French version would useWITH unaccent, french_stem. - Stop words run after unaccent. A stop word list that contains accented entries may no longer match, because the token reaches the stemmer already stripped. Check your stop word list against the unaccented forms.
Adjusting the unaccent rules
The unaccent dictionary reads its character mappings from a rules file. The default file covers most Latin-script diacritics, and some characters expand, such as ß becoming ss. If you need different mappings, you can create a dictionary from the unaccent template that points to your own rules file:
CREATE TEXT SEARCH DICTIONARY my_unaccent (
TEMPLATE = unaccent,
RULES = 'my_unaccent'
);PostgreSQL looks for my_unaccent.rules in the server's tsearch_data directory. That needs file access on the database server, so it is often unavailable on managed services. Check what your provider allows before relying on it.
Summary of the steps
- Install the
unaccentextension. - Copy a built-in configuration with
CREATE TEXT SEARCH CONFIGURATION ... (COPY = ...). - Remap
hword,hword_part, andwordtounaccentfollowed by the stemmer. - Verify with
to_tsvectorandts_debug. - Rebuild the stored
tsvectorcolumn and its index with the new configuration. - Use the same configuration name in every query constructor.
Exercise
You changed my_english with ALTER TEXT SEARCH CONFIGURATION after the search column was already populated. Searches for cafe still miss documents containing café. Why, and what do you do?
Show answer
The stored tsvector values were built with the old mapping, so they still contain the accented lexeme. Changing the configuration does not regenerate them. Rebuild the column, by dropping and re-adding it (or using SET EXPRESSION on PostgreSQL 17 and later), then recreate the GIN index. In future, create a new configuration name instead of altering one that stored data depends on.
Exercise
A colleague writes ALTER TEXT SEARCH CONFIGURATION my_english ALTER MAPPING FOR word WITH english_stem, unaccent;. What goes wrong?
Show answer
The order is reversed. english_stem accepts the token first, so the chain stops and unaccent never runs. The mapping should be WITH unaccent, english_stem. Also, the mapping omits hword and hword_part, so hyphenated words would still keep their accents.