12.8. Тестирование и отладка текстового поиска
Поведение нестандартной конфигурации текстового поиска по мере её усложнения может стать непонятным. В этом разделе описаны функции, полезные для тестирования объектов текстового поиска. Вы можете тестировать конфигурацию как целиком, так и по частям, отлаживая анализаторы и словари по отдельности.
12.8.1. Тестирование конфигурации
Созданную конфигурацию текстового поиска можно легко протестировать с помощью функции ts_debug
.
ts_debug([конфигурация
regconfig
,]документ
text
, OUTпсевдоним
text
, OUTописание
text
, OUTфрагмент
text
, OUTсловари
regdictionary[]
, OUTсловарь
regdictionary
, OUTлексемы
text[]
) returns setof record
ts_debug
выводит информацию обо всех фрагментах данного документа, которые были выданы анализатором и обработаны настроенными словарями. Она использует конфигурацию, указанную в аргументе config
, или default_text_search_config
, если этот аргумент опущен.
ts_debug
возвращает по одной строке для каждого фрагмента, найденного в тексте анализатором. Эта строка содержит следующие столбцы:
синоним
text
— краткое имя типа фрагментаописание
text
— описание типа фрагментафрагмент
text
— текст фрагментасловари
regdictionary[]
— словари, назначенные в конфигурации для фрагментов такого типасловарь
regdictionary
— словарь, распознавший этот фрагмент, илиNULL
, если подходящего словаря не нашлосьлексемы
text[]
— лексемы, выданные словарём, распознавшим фрагмент, илиNULL
, если подходящий словарь не нашёлся; может быть также пустым массивом ({}
), если фрагмент распознан как стоп-слово
Простой пример:
SELECT * FROM ts_debug('english', 'a fat cat sat on a mat - it ate a fat rats'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------+----------------+--------------+--------- asciiword | Word, all ASCII | a | {english_stem} | english_stem | {} blank | Space symbols | | {} | | asciiword | Word, all ASCII | fat | {english_stem} | english_stem | {fat} blank | Space symbols | | {} | | asciiword | Word, all ASCII | cat | {english_stem} | english_stem | {cat} blank | Space symbols | | {} | | asciiword | Word, all ASCII | sat | {english_stem} | english_stem | {sat} blank | Space symbols | | {} | | asciiword | Word, all ASCII | on | {english_stem} | english_stem | {} blank | Space symbols | | {} | | asciiword | Word, all ASCII | a | {english_stem} | english_stem | {} blank | Space symbols | | {} | | asciiword | Word, all ASCII | mat | {english_stem} | english_stem | {mat} blank | Space symbols | | {} | | blank | Space symbols | - | {} | | asciiword | Word, all ASCII | it | {english_stem} | english_stem | {} blank | Space symbols | | {} | | asciiword | Word, all ASCII | ate | {english_stem} | english_stem | {ate} blank | Space symbols | | {} | | asciiword | Word, all ASCII | a | {english_stem} | english_stem | {} blank | Space symbols | | {} | | asciiword | Word, all ASCII | fat | {english_stem} | english_stem | {fat} blank | Space symbols | | {} | | asciiword | Word, all ASCII | rats | {english_stem} | english_stem | {rat}
Для более полной демонстрации мы сначала создадим конфигурацию public.english
и словарь Ispell для английского языка:
CREATE TEXT SEARCH CONFIGURATION public.english ( COPY = pg_catalog.english ); CREATE TEXT SEARCH DICTIONARY english_ispell ( TEMPLATE = ispell, DictFile = english, AffFile = english, StopWords = english ); ALTER TEXT SEARCH CONFIGURATION public.english ALTER MAPPING FOR asciiword WITH english_ispell, english_stem;
SELECT * FROM ts_debug('public.english', 'The Brightest supernovaes'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------------+-------------------------------+----------------+------------- asciiword | Word, all ASCII | The | {english_ispell,english_stem} | english_ispell | {} blank | Space symbols | | {} | | asciiword | Word, all ASCII | Brightest | {english_ispell,english_stem} | english_ispell | {bright} blank | Space symbols | | {} | | asciiword | Word, all ASCII | supernovaes | {english_ispell,english_stem} | english_stem | {supernova}
В этом примере слово Brightest
было воспринято анализатором как фрагмент ASCII word
(синоним asciiword
). Для этого типа фрагментов список словарей включает english_ispell
и english_stem
. Данное слово было распознано словарём english_ispell
, который свёл его к bright
. Слово supernovaes
оказалось незнакомо словарю english_ispell
, так что оно было передано следующему словарю, который его благополучно распознал (на самом деле english_stem
— это стеммер Snowball, который распознаёт всё, поэтому он включён в список словарей последним).
Слово The
было распознано словарём english_ispell
как стоп-слово (см. Подраздел 12.6.1) и поэтому не будет индексироваться. Пробелы тоже отбрасываются, так как в данной конфигурации для них нет словарей.
Вы можете уменьшить ширину вывода, явно перечислив только те столбцы, которые вы хотите видеть:
SELECT alias, token, dictionary, lexemes FROM ts_debug('public.english', 'The Brightest supernovaes'); alias | token | dictionary | lexemes -----------+-------------+----------------+------------- asciiword | The | english_ispell | {} blank | | | asciiword | Brightest | english_ispell | {bright} blank | | | asciiword | supernovaes | english_stem | {supernova}
12.8.2. Тестирование анализатора
Следующие функции позволяют непосредственно протестировать анализатор текстового поиска.
ts_parse(имя_анализатора
text
,документ
text
, OUTкод_фрагмента
integer
, OUTфрагмент
text
) returnssetof record
ts_parse(oid_анализатора
oid
,документ
text
, OUTкод_фрагмента
integer
, OUTфрагмент
text
) returnssetof record
ts_parse
разбирает данный документ и возвращает набор записей, по одной для каждого извлечённого фрагмента. Каждая запись содержит код_фрагмента
, код назначенного типа фрагмента, и фрагмент
, собственно текст фрагмента. Например:
SELECT * FROM ts_parse('default', '123 - a number'); tokid | token -------+-------- 22 | 123 12 | 12 | - 1 | a 12 | 1 | number
ts_token_type(имя_анализатора
text
, OUTкод_фрагмента
integer
, OUTпсевдоним
text
, OUTописание
text
) returnssetof record
ts_token_type(oid_анализатора
oid
, OUTкод_фрагмента
integer
, OUTпсевдоним
text
, OUTописание
text
) returnssetof record
ts_token_type
возвращает таблицу, описывающую все типы фрагментов, которые может распознать анализатор. Для каждого типа в этой таблице указывается целочисленный tokid
(идентификатор), который анализатор использует для пометки фрагмента этого типа, alias
(псевдоним), с которым этот тип фигурирует в командах конфигурации, и description
(краткое описание). Например:
SELECT * FROM ts_token_type('default'); tokid | alias | description -------+-----------------+------------------------------------------ 1 | asciiword | Word, all ASCII 2 | word | Word, all letters 3 | numword | Word, letters and digits 4 | email | Email address 5 | url | URL 6 | host | Host 7 | sfloat | Scientific notation 8 | version | Version number 9 | hword_numpart | Hyphenated word part, letters and digits 10 | hword_part | Hyphenated word part, all letters 11 | hword_asciipart | Hyphenated word part, all ASCII 12 | blank | Space symbols 13 | tag | XML tag 14 | protocol | Protocol head 15 | numhword | Hyphenated word, letters and digits 16 | asciihword | Hyphenated word, all ASCII 17 | hword | Hyphenated word, all letters 18 | url_path | URL path 19 | file | File or path name 20 | float | Decimal notation 21 | int | Signed integer 22 | uint | Unsigned integer 23 | entity | XML entity
12.8.3. Тестирование словаря
Для тестирования словаря предназначена функция ts_lexize
.
ts_lexize(словарь
regdictionary
,фрагмент
text
) returnstext[]
ts_lexize
возвращает массив лексем, если входной фрагмент
известен словарю, либо пустой массив, если этот фрагмент считается в словаре стоп-словом, либо NULL
, если он не был распознан.
Примеры:
SELECT ts_lexize('english_stem', 'stars'); ts_lexize ----------- {star} SELECT ts_lexize('english_stem', 'a'); ts_lexize ----------- {}
Примечание
Функция ts_lexize
принимает одиночный фрагмент, а не просто текст. Вот пример возможного заблуждения:
SELECT ts_lexize('thesaurus_astro', 'supernovae stars') is null; ?column? ---------- t
Хотя фраза supernovae stars
есть в тезаурусе thesaurus_astro
, ts_lexize
не работает, так как она не разбирает входной текст, а воспринимает его как один фрагмент. Поэтому для проверки тезаурусов следует использовать функции plainto_tsquery
и to_tsvector
, например:
SELECT plainto_tsquery('supernovae stars'); plainto_tsquery ----------------- 'sn'
48.46. pg_statistic
The catalog pg_statistic
stores statistical data about the contents of the database. Entries are created by ANALYZE and subsequently used by the query planner. Note that all the statistical data is inherently approximate, even assuming that it is up-to-date.
Normally there is one entry, with stainherit
= false
, for each table column that has been analyzed. If the table has inheritance children, a second entry with stainherit
= true
is also created. This row represents the column's statistics over the inheritance tree, i.e., statistics for the data you'd see with SELECT
, whereas the column
FROM table
*stainherit
= false
row represents the results of SELECT
. column
FROM ONLY table
pg_statistic
also stores statistical data about the values of index expressions. These are described as if they were actual data columns; in particular, starelid
references the index. No entry is made for an ordinary non-expression index column, however, since it would be redundant with the entry for the underlying table column. Currently, entries for index expressions always have stainherit
= false
.
Since different kinds of statistics might be appropriate for different kinds of data, pg_statistic
is designed not to assume very much about what sort of statistics it stores. Only extremely general statistics (such as nullness) are given dedicated columns in pg_statistic
. Everything else is stored in “slots”, which are groups of associated columns whose content is identified by a code number in one of the slot's columns. For more information see src/include/catalog/pg_statistic.h
.
pg_statistic
should not be readable by the public, since even statistical information about a table's contents might be considered sensitive. (Example: minimum and maximum values of a salary column might be quite interesting.) pg_stats
is a publicly readable view on pg_statistic
that only exposes information about those tables that are readable by the current user.
Table 48.46. pg_statistic
Columns
Name | Type | References | Description |
---|---|---|---|
starelid | oid |
| The table or index that the described column belongs to |
staattnum | int2 |
| The number of the described column |
stainherit | bool | If true, the stats include inheritance child columns, not just the values in the specified relation | |
stanullfrac | float4 | The fraction of the column's entries that are null | |
stawidth | int4 | The average stored width, in bytes, of nonnull entries | |
stadistinct | float4 | The number of distinct nonnull data values in the column. A value greater than zero is the actual number of distinct values. A value less than zero is the negative of a multiplier for the number of rows in the table; for example, a column in which about 80% of the values are nonnull and each nonnull value appears about twice on average could be represented by stadistinct = -0.4. A zero value means the number of distinct values is unknown. | |
stakind | int2 | A code number indicating the kind of statistics stored in the N th “slot” of the pg_statistic row. | |
staop | oid |
| An operator used to derive the statistics stored in the N th “slot”. For example, a histogram slot would show the < operator that defines the sort order of the data. |
stanumbers | float4[] | Numerical statistics of the appropriate kind for the N th “slot”, or null if the slot kind does not involve numerical values | |
stavalues | anyarray | Column data values of the appropriate kind for the N th “slot”, or null if the slot kind does not store any data values. Each array's element values are actually of the specific column's data type, or a related type such as an array's element type, so there is no way to define these columns' type more specifically than anyarray . |