Sub topic 15
Building a Custom Configuration with `unaccent`
This chapter assumes you know basic SQL, can create PostgreSQL extensions and indexes, and have used tsvector and tsquery. You will configure PostgreSQL so accented and unaccented spellings match during full-text search.
Why customize a text search configuration?
A text search configuration connects a parser to dictionaries. The parser identifies tokens, such as words. Dictionaries transform those tokens into lexemes, which are the normalized terms stored in a tsvector.
The built-in english configuration handles stemming. For example, running and runs can become the same lexeme. It does not, however, automatically make café match cafe.
The unaccent extension removes diacritics. By placing its dictionary before the English stemmer, PostgreSQL first changes café to cafe, then applies English stemming.
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;COPY = english preserves the standard parser and mappings. The ALTER MAPPING statement changes how the most common word token types are processed. PostgreSQL tries unaccent first. The resulting text then goes to english_stem.
Use the configuration for documents and queries
Use the same configuration on both sides of a search. Otherwise, a document and its query can be normalized differently.
SELECT to_tsvector('my_english', 'Café résumé runners');
SELECT to_tsquery('my_english', 'cafe & run');
SELECT to_tsvector('my_english', 'Café résumé runners')
@@ to_tsquery('my_english', 'cafe & run') AS matches;The first expression produces lexemes for the accented words. The second normalizes the query terms. The final expression returns true when the normalized query matches the normalized document.
A generated column can use this configuration:
CREATE TABLE products (
id bigserial PRIMARY KEY,
name text NOT NULL,
search tsvector GENERATED ALWAYS AS (
to_tsvector('my_english', name)
) STORED
);
CREATE INDEX products_search_idx
ON products USING gin (search);If you later change the configuration, existing generated values may need to be recomputed. Plan that change as a schema migration and test it against real search terms.
Inspect the result
Use ts_debug to see which parser token and dictionaries PostgreSQL uses.
SELECT alias, token, dictionaries, lexemes
FROM ts_debug('my_english', 'Café résumé');A typical result shows unaccent producing unaccented text and english_stem producing the final lexeme. This is useful when a search unexpectedly returns no rows.
Exercise
Why must a query use my_english when the indexed document uses my_english?
Show answer
Both sides must produce compatible lexemes. Using different configurations can leave accents or apply different stemming rules, so an expected match may fail.