F.16. dict_xsyn
Модуль dict_xsyn (Extended Synonym Dictionary, расширенный словарь синонимов) представляет собой пример дополнительного шаблона словаря для полнотекстового поиска. Этот словарь заменяет слова группами их синонимов, что позволяет находить слово по одному из его синонимов.
F.16.1. Конфигурирование
Словарь dict_xsyn принимает следующие параметры:
Параметр
matchorigопределяет, будет ли словарь принимать изначальное слово. По умолчанию он включён (имеет значениеtrue).Параметр
matchsynonymsопределяет, будет ли словарь принимать синонимы. По умолчанию он отключён (имеет значениеfalse).Параметр
keeporigопределяет, будет ли исходное слово включаться в вывод словаря. По умолчанию он включён (имеет значениеtrue).Параметр
keepsynonymsопределяет, будут ли в вывод словаря включаться синонимы. По умолчанию он включён (имеет значениеtrue).Параметр
rulesзадаёт базовое имя файла со списком синонимов. Этот файл должен находиться в каталоге$SHAREDIR/tsearch_data/(где под$SHAREDIRпонимается каталог с общими данными инсталляции Postgres Pro). Имя файла должно заканчиваться расширением.rules(которое не нужно указывать в параметреrules).
Файл правил имеет следующий формат:
Каждая строка представляет группу синонимов для одного слова, которое задаётся первым в этой строке. Символы разделяются пробельными символами, так что строка выглядит так:
word syn1 syn2 syn3
Символ решётки (
#) обозначает начало комментария. Он может находиться в любом месте строки. Следующая за ним часть строки игнорируется.
Пример словаря можно найти в файле xsyn_sample.rules, устанавливаемом в $SHAREDIR/tsearch_data/.
F.16.2. Использование
При установке расширения dict_xsyn в базе создаётся шаблон текстового поиска xsyn_template и словарь xsyn на его базе, с параметрами по умолчанию. Вы можете изменить параметры словаря, например так:
mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=false); ALTER TEXT SEARCH DICTIONARY
или создать новые словари на базе этого шаблона.
Протестировать этот словарь можно так:
mydb=# SELECT ts_lexize('xsyn', 'word');
ts_lexize
-----------------------
{syn1,syn2,syn3}
mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=true);
ALTER TEXT SEARCH DICTIONARY
mydb=# SELECT ts_lexize('xsyn', 'word');
ts_lexize
-----------------------
{word,syn1,syn2,syn3}
mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=false, MATCHSYNONYMS=true);
ALTER TEXT SEARCH DICTIONARY
mydb=# SELECT ts_lexize('xsyn', 'syn1');
ts_lexize
-----------------------
{syn1,syn2,syn3}
mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=true, MATCHORIG=false, KEEPSYNONYMS=false);
ALTER TEXT SEARCH DICTIONARY
mydb=# SELECT ts_lexize('xsyn', 'syn1');
ts_lexize
-----------------------
{word}Но для практического применения его нужно включить в конфигурацию текстового поиска, как описано в Главе 12. Это может выглядеть примерно так:
ALTER TEXT SEARCH CONFIGURATION english
ALTER MAPPING FOR word, asciiword WITH xsyn, english_stem;F.16. dict_xsyn
dict_xsyn (Extended Synonym Dictionary) is an example of an add-on dictionary template for full-text search. This dictionary type replaces words with groups of their synonyms, and so makes it possible to search for a word using any of its synonyms.
F.16.1. Configuration
A dict_xsyn dictionary accepts the following options:
matchorigcontrols whether the original word is accepted by the dictionary. Default istrue.matchsynonymscontrols whether the synonyms are accepted by the dictionary. Default isfalse.keeporigcontrols whether the original word is included in the dictionary's output. Default istrue.keepsynonymscontrols whether the synonyms are included in the dictionary's output. Default istrue.rulesis the base name of the file containing the list of synonyms. This file must be stored in$SHAREDIR/tsearch_data/(where$SHAREDIRmeans the Postgres Pro installation's shared-data directory). Its name must end in.rules(which is not to be included in therulesparameter).
The rules file has the following format:
Each line represents a group of synonyms for a single word, which is given first on the line. Synonyms are separated by whitespace, thus:
word syn1 syn2 syn3
The sharp (
#) sign is a comment delimiter. It may appear at any position in a line. The rest of the line will be skipped.
Look at xsyn_sample.rules, which is installed in $SHAREDIR/tsearch_data/, for an example.
F.16.2. Usage
Installing the dict_xsyn extension creates a text search template xsyn_template and a dictionary xsyn based on it, with default parameters. You can alter the parameters, for example
mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=false); ALTER TEXT SEARCH DICTIONARY
or create new dictionaries based on the template.
To test the dictionary, you can try
mydb=# SELECT ts_lexize('xsyn', 'word');
ts_lexize
-----------------------
{syn1,syn2,syn3}
mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=true);
ALTER TEXT SEARCH DICTIONARY
mydb=# SELECT ts_lexize('xsyn', 'word');
ts_lexize
-----------------------
{word,syn1,syn2,syn3}
mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=false, MATCHSYNONYMS=true);
ALTER TEXT SEARCH DICTIONARY
mydb=# SELECT ts_lexize('xsyn', 'syn1');
ts_lexize
-----------------------
{syn1,syn2,syn3}
mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=true, MATCHORIG=false, KEEPSYNONYMS=false);
ALTER TEXT SEARCH DICTIONARY
mydb=# SELECT ts_lexize('xsyn', 'syn1');
ts_lexize
-----------------------
{word}
Real-world usage will involve including it in a text search configuration as described in Chapter 12. That might look like this:
ALTER TEXT SEARCH CONFIGURATION english
ALTER MAPPING FOR word, asciiword WITH xsyn, english_stem;