Sub topic 14
Dictionaries: stop words, stemming, synonyms and thesaurus
This chapter assumes you have read the chapters on text search configurations, tsvector and tsquery. You should be comfortable with to_tsvector, ts_debug and ALTER TEXT SEARCH CONFIGURATION. Here you will look at what a configuration does with each token: it hands the token to a chain of dictionaries.
What a dictionary does
A dictionary is a function that takes one token and returns one of three results:
- An array of one or more lexemes. The token is recognized, and these lexemes go into the
tsvector. - An empty array. The token is recognized as a stop word and is discarded.
NULL. The dictionary does not recognize the token, so the next dictionary in the list gets it.
A configuration maps each token type (asciiword, numword, email and so on) to an ordered list of dictionaries. The first dictionary that returns something other than NULL decides the outcome. If no dictionary recognizes a token, the token is dropped.
The order matters. Put narrow, specific dictionaries (synonyms, thesauri) first and a broad one (a stemmer) last. A stemmer recognizes every word, so any dictionary listed after it is never reached.
Testing a dictionary with ts_lexize
ts_lexize runs one dictionary on one token, which makes the three results visible.
SELECT ts_lexize('english_stem', 'stars'); -- {star}
SELECT ts_lexize('english_stem', 'running'); -- {run}
SELECT ts_lexize('english_stem', 'the'); -- {} (stop word)
SELECT ts_lexize('simple', 'The'); -- {the}The simple dictionary only lowercases. It has no stop word list unless you give it one, so it keeps the. A configuration that uses only simple therefore indexes every word exactly as written, apart from case.
To see which dictionaries a configuration applies, run ts_debug on a sample sentence and read the dictionaries and dictionary columns. \dF+ english in psql prints the full mapping table.
Stop words
Stop words are very common words, such as the, of and and, that add little to a search. Dictionaries that support them (simple, snowball, ispell) read them from a .stop file with one word per line. The files live in the tsearch_data directory under the server's shared directory. pg_config --sharedir prints its parent.
Two behaviors surprise people:
- Stop words keep their position numbers. The words are removed, but the counter still advances.
- A query made only of stop words matches nothing. PostgreSQL emits a notice and ignores the query.
SELECT to_tsvector('english', 'in the list of stop words');
-- 'list':3 'stop':5 'word':6
SELECT to_tsquery('english', 'the & of');
-- NOTICE: text-search query contains only stop words or doesn't contain lexemes, ignoredBecause positions are preserved, phrase search still respects the distance between words. phraseto_tsquery('english', 'fox of the hill') produces a <3> distance between fox and hill, not <->.
To use your own stop list, create a snowball dictionary that points to a file you add to tsearch_data:
CREATE TEXT SEARCH DICTIONARY english_custom_stem (
TEMPLATE = snowball,
Language = english,
StopWords = my_stopwords
);Here my_stopwords.stop must exist on the database server. Managed services usually do not let you place files there, so check this before you plan around file-based dictionaries.
Stemming
A stemmer reduces a word to a root form, so foxes, fox and fox's map to the same lexeme. The built-in language configurations use Snowball stemmers, named english_stem, german_stem and so on. A Snowball stemmer is rule-based, not a lookup table, so its output is not always a real word. ts_lexize('english_stem', 'universities') returns {univers}. That is fine, because the query side is stemmed the same way.
Stemming has costs:
- It over-merges. Rule-based stemmers can map unrelated words to one root.
- It under-merges. Irregular forms such as
miceandmousemay not meet. - It is language-specific. A configuration for English will stem German text poorly.
The ispell template can use Hunspell-style dictionary files. It handles irregular forms and compound words better, but it needs .dict and .affix files on the server, and loading a large one costs memory in each session. Most applications are well served by Snowball.
Synonym dictionaries
A synonym dictionary replaces one word with another before any stemming. Use it for product names, abbreviations and spelling variants that you want treated as one term.
The mapping lives in a .syn file in tsearch_data. Each line has an input word followed by the lexeme to emit. For example, pg_synonyms.syn might contain:
postgres pgsql
postgresql pgsql
pg pgsqlThen create the dictionary and put it ahead of the stemmer:
CREATE TEXT SEARCH DICTIONARY tech_synonyms (
TEMPLATE = synonym,
SYNONYMS = pg_synonyms
);
CREATE TEXT SEARCH CONFIGURATION tech_english (COPY = english);
ALTER TEXT SEARCH CONFIGURATION tech_english
ALTER MAPPING FOR asciiword, asciihword, hword_asciipart
WITH tech_synonyms, english_stem;
SELECT to_tsvector('tech_english', 'Postgres and PostgreSQL');
-- 'pgsql':1,3Matching on the input word is case-insensitive by default. The replacement is emitted exactly as written in the file and is not stemmed, so write it in the form you want stored. Words not in the file return NULL, so and falls through to english_stem and is dropped as a stop word.
Thesaurus dictionaries
A thesaurus dictionary is a synonym dictionary that understands phrases. Each line of the .ths file maps a phrase to the lexeme to index, separated by a colon:
supernovae stars : sn
crab nebulae : crabA thesaurus normalizes the words in the phrase with a subdictionary before comparing, so supernova star would also match the first line. You name the subdictionary when you create it:
CREATE TEXT SEARCH DICTIONARY thesaurus_astro (
TEMPLATE = thesaurus,
DictFile = thesaurus_astro,
Dictionary = english_stem
);
ALTER TEXT SEARCH CONFIGURATION tech_english
ALTER MAPPING FOR asciiword, asciihword, hword_asciipart
WITH thesaurus_astro, tech_synonyms, english_stem;The thesaurus must come before the stemmer. Otherwise the stemmer consumes each word individually and the phrase is never seen.
Gotchas when you change dictionaries
- Stored vectors go stale. Changing a dictionary or a mapping does not rewrite existing
tsvectorvalues. Queries are processed with the new rules while stored documents keep the old lexemes, so matches silently disappear. After a change, rebuild the stored column by rewriting the rows, then reindex. - Files load per session. A session reads a dictionary file when it first uses the dictionary. Existing connections may keep the old content, so reconnect to test file edits.
- Files need the right form. Dictionary files must be UTF-8 and use the expected extension (
.syn,.ths,.stop). - Use the same configuration on both sides. A document built with
tech_englishand a query built withenglishproduce different lexemes for the same text.
Choosing between the options
| Need | Use |
|---|---|
| Drop filler words | A `.stop` file via `snowball` or `simple` |
| Match word forms (`run`, `running`) | A Snowball stemmer such as `english_stem` |
| Map names and abbreviations to one term | `synonym` dictionary |
| Map multi-word phrases to one term | `thesaurus` dictionary |
| Irregular forms and compounds | `ispell` dictionary |
Exercise
A configuration maps asciiword to english_stem, tech_synonyms. You add the line pg pgsql to the synonym file, but searching for pg never returns documents containing pgsql. Why, and how do you fix it?
Show answer
english_stem is a stemmer that recognizes every word, so it returns lexemes for pg and the token never reaches tech_synonyms. Reorder the mapping so the synonym dictionary comes first (WITH tech_synonyms, english_stem). Then rewrite any stored tsvector values and reindex, because existing documents still hold the old lexemes.