F.50. shared_ispell

Модуль shared_ispell предоставляет разделяемый словарь ispell, то есть словарь, расположенный в общем сегменте памяти. В традиционной реализации ispell каждый сеанс инициализирует и загружает собственный экземпляр словаря, и на это уходит много ресурсов процессора и памяти.

Это расширение выделяет область памяти в разделяемом сегменте (вы должны выбрать его размер заранее) и загружает в неё словарь при первом использовании.

F.50.1. Функции

Реализованные в модуле shared_ispell функции перечислены в Таблице F.32.

Таблица F.32. Функции shared_ispell

ФункцияВозвращаетОписание
shared_ispell_reset()voidСбрасывает словари (например, для повторной загрузки изменённых файлов с диска). Сеансы, в которых словари уже использовались, будут должны переинициализировать их.
shared_ispell_mem_used()intВозвращает объём памяти, используемой загруженными словарями в разделяемом сегменте (в байтах).
shared_ispell_mem_available()intВозвращает объём доступной памяти в разделяемом сегменте.
shared_ispell_dicts()setof(dict_name varchar, affix_name varchar, words int, affixes int, bytes int)Возвращает список словарей, загруженных в разделяемый сегмент.
shared_ispell_stoplists()setof(stop_name varchar, words int, bytes int)Возвращает список наборов стоп-слов, загруженных в разделяемый сегмент.

F.50.2. Параметры GUC

shared_ispell.max_size (int)

Определяет максимальный размер разделяемого сегмента. Это жёсткий предел; разделяемый сегмент нельзя расширить, поэтому нужно установить такой размер, чтобы в этом сегменте уместились все словари и при этом он не занимал лишний объём.

F.50.3. Использование словаря

Этот модуль должен выделить область памяти в разделяемом сегменте. Поэтому добавьте в файл конфигурации следующие параметры (или отредактируйте текущие значения):

# загружаемые библиотеки
shared_preload_libraries = 'shared_ispell'

# объём разделяемой памяти
shared_ispell.max_size = 32MB

Чтобы понять, сколько памяти вам действительно нужно, задайте сначала большое значение (например, 200 МБ) и загрузите все нужные вам словари. Затем воспользуйтесь функцией shared_ispell_mem_used() и определите, сколько памяти на самом деле используется (и скорректируйте соответствующую переменную GUC shared_ispell.max_size).

Не задавайте в точности полученное значение, оставьте небольшой резерв, чтобы вы могли перезагружать словари, не изменяя предел GUC max_size (что потребует перезапуска БД). Объёма в районе 512 КБ будет вполне достаточно.

Это расширение определяет шаблон shared_ispell, используя который можно определять собственные словари текстового поиска. Например, вы можете сделать следующее:

CREATE TEXT SEARCH DICTIONARY english_shared (
    TEMPLATE = shared_ispell,
    DictFile = en_us,
    AffFile = en_us,
    StopWords = english
);

CREATE TEXT SEARCH CONFIGURATION public.english_shared
    ( COPY = pg_catalog.simple );

ALTER TEXT SEARCH CONFIGURATION english_shared
    ALTER MAPPING FOR asciiword, asciihword, hword_asciipart,
                    word, hword, hword_part
    WITH english_shared, english_stem;

Проверить полученную конфигурацию можно так:

SELECT * FROM ts_debug('english_shared', 'abilities');
   alias   |   description   |   token   |         dictionaries          |   dictionary   |  lexemes  
-----------+-----------------+-----------+-------------------------------+----------------+-----------
 asciiword | Word, all ASCII | abilities | {english_shared,english_stem} | english_shared | {ability}
(1 row)

Вы также можете изменить существующую конфигурацию текстового поиска. Например, если у вас есть конфигурация public.english, вы можете подключить к ней шаблон shared_ispell:

ALTER TEXT SEARCH CONFIGURATION public.english
    ALTER MAPPING FOR asciiword, asciihword, hword_asciipart,
                    word, hword, hword_part
    WITH english_shared, english_stem;

F.50.4. Автор

Томаш Вондра , Прага, Чешская республика

F.50. shared_ispell

The shared_ispell module provides a shared ispell dictionary, i.e. a dictionary that's stored in shared segment. The traditional ispell implementation means that each session initializes and stores the dictionary on it's own, which means a lot of CPU/RAM is wasted.

This extension allocates an area in shared segment (you have to choose the size in advance) and then loads the dictionary into it when it's used for the first time.

F.50.1. Functions

The functions provided by the shared_ispell module are shown in Table F.32.

Table F.32. shared_ispell Functions

FunctionReturnsDescription
shared_ispell_reset()void Resets the dictionaries (e.g. so that you can reload the updated files from disk). The sessions that already use the dictionaries will be forced to reinitialize them.
shared_ispell_mem_used()int Returns a value of used memory of the shared segment by loaded shared dictionaries in bytes.
shared_ispell_mem_available()int Returns a value of available memory of the shared segment.
shared_ispell_dicts()setof(dict_name varchar, affix_name varchar, words int, affixes int, bytes int) Returns a list of dictionaries loaded in the shared segment.
shared_ispell_stoplists()setof(stop_name varchar, words int, bytes int) Returns a list of stopwords loaded in the shared segment.

F.50.2. GUC Parameters

shared_ispell.max_size (int)

Defines the maximum size of the shared segment. This is a hard limit, the shared segment is not extensible and you need to set it so that all the dictionaries fit into it and not much memory is wasted.

F.50.3. Using the dictionary

The module needs to allocate space in the shared memory segment. So add this to the config file (or update the current values):

# libraries to load
shared_preload_libraries = 'shared_ispell'

# config of the shared memory
shared_ispell.max_size = 32MB

To find out how much memory you actually need, use a large value (e.g. 200MB) and load all the dictionaries you want to use. Then use the shared_ispell_mem_used() function to find out how much memory was actually used (and set the shared_ispell.max_size GUC variable accordingly).

Don't set it exactly to that value, leave there some free space, so that you can reload the dictionaries without changing the GUC max_size limit (which requires a restart of the DB). Something like 512kB should be just fine.

The extension defines a shared_ispell template that you may use to define custom dictionaries. E.g. you may do this:

CREATE TEXT SEARCH DICTIONARY english_shared (
    TEMPLATE = shared_ispell,
    DictFile = en_us,
    AffFile = en_us,
    StopWords = english
);

CREATE TEXT SEARCH CONFIGURATION public.english_shared
    ( COPY = pg_catalog.simple );

ALTER TEXT SEARCH CONFIGURATION english_shared
    ALTER MAPPING FOR asciiword, asciihword, hword_asciipart,
                    word, hword, hword_part
    WITH english_shared, english_stem;

We can test created configuration:

SELECT * FROM ts_debug('english_shared', 'abilities');
   alias   |   description   |   token   |         dictionaries          |   dictionary   |  lexemes  
-----------+-----------------+-----------+-------------------------------+----------------+-----------
 asciiword | Word, all ASCII | abilities | {english_shared,english_stem} | english_shared | {ability}
(1 row)

Or you can update your own text search configuration. For example, you have the public.english dictionary. You can update it to use the shared_ispell template:

ALTER TEXT SEARCH CONFIGURATION public.english
    ALTER MAPPING FOR asciiword, asciihword, hword_asciipart,
                    word, hword, hword_part
    WITH english_shared, english_stem;

F.50.4. Author

Tomas Vondra , Prague, Czech Republic

FAQ