12.5. Анализаторы
Задача анализаторов текста — разделить текст документа на фрагменты и присвоить каждому из них тип из набора, определённого в самом анализаторе. Заметьте, что анализаторы не меняют текст — они просто выдают позиции предполагаемых слов. Вследствие такой ограниченности их функций, собственные специфические анализаторы бывают нужны гораздо реже, чем собственные словари. В настоящее время в Postgres Pro есть только один встроенный анализатор, который может быть полезен для широкого круга приложений.
Этот встроенный анализатор называется pg_catalog.default
. Он распознаёт 23 типа фрагментов, перечисленные в Таблице 12.1.
Таблица 12.1. Типы фрагментов, выделяемых стандартным анализатором
Псевдоним | Описание | Пример |
---|---|---|
asciiword | Слово только из букв ASCII | elephant |
word | Слово из любых букв | mañana |
numword | Слово из букв и цифр | beta1 |
asciihword | Слово только из букв ASCII с дефисами | up-to-date |
hword | Слово из любых букв с дефисами | lógico-matemática |
numhword | Слово из букв и цифр с дефисами | postgresql-beta1 |
hword_asciipart | Часть слова с дефисами, только из букв ASCII | postgresql в словосочетании postgresql-beta1 |
hword_part | Часть слова с дефисами, из любых букв | lógico или matemática в словосочетании lógico-matemática |
hword_numpart | Часть слова с дефисами, из букв и цифр | beta1 в словосочетании postgresql-beta1 |
email | Адрес электронной почты | foo@example.com |
protocol | Префикс протокола | http:// |
url | URL | example.com/stuff/index.html |
host | Имя узла | example.com |
url_path | Путь в адресе URL | /stuff/index.html , как часть URL |
файл | Путь или имя файла | /usr/local/foo.txt , если не является частью URL |
sfloat | Научная запись числа | -1.234e56 |
float | Десятичная запись числа | -1.234 |
int | Целое со знаком | -1234 |
uint | Целое без знака | 1234 |
version | Номер версии | 8.3.0 |
tag | Тег XML | <a href="dictionaries.html"> |
entity | Сущность XML | & |
blank | Символы-разделители | (любые пробельные символы или знаки препинания, не попавшие в другие категории) |
Примечание
Понятие «буквы» анализатор определяет исходя из локали, заданной для базы данных, в частности параметра lc_ctype
. Слова, содержащие только буквы из ASCII (латинские буквы), распознаются как фрагменты отдельного типа, так как иногда бывает полезно выделить их. Для многих европейских языков типы фрагментов word
и asciiword
можно воспринимать как синонимы.
email
принимает не все символы, которые считаются допустимыми по стандарту RFC 5322. В частности, имя почтового ящика помимо алфавитно-цифровых символов может содержать только точку, минус и подчёркивание.
Анализатор может выделить в одном тексте несколько перекрывающихся фрагментов. Например, слово с дефисом будет выдано как целое составное слово и по частям:
SELECT alias, description, token FROM ts_debug('foo-bar-beta1'); alias | description | token -----------------+------------------------------------------+-------------- numhword | Hyphenated word, letters and digits | foo-bar-beta1 hword_asciipart | Hyphenated word part, all ASCII | foo blank | Space symbols | - hword_asciipart | Hyphenated word part, all ASCII | bar blank | Space symbols | - hword_numpart | Hyphenated word part, letters and digits | beta1
Это поведение считается желательным, так как это позволяет находить при последующем поиске и всё слово целиком, и его части. Ещё один показательный пример:
SELECT alias, description, token FROM ts_debug('http://example.com/stuff/index.html'); alias | description | token ----------+---------------+------------------------------ protocol | Protocol head | http:// url | URL | example.com/stuff/index.html host | Host | example.com url_path | URL path | /stuff/index.html
12.5. Parsers
Text search parsers are responsible for splitting raw document text into tokens and identifying each token's type, where the set of possible types is defined by the parser itself. Note that a parser does not modify the text at all — it simply identifies plausible word boundaries. Because of this limited scope, there is less need for application-specific custom parsers than there is for custom dictionaries. At present Postgres Pro provides just one built-in parser, which has been found to be useful for a wide range of applications.
The built-in parser is named pg_catalog.default
. It recognizes 23 token types, shown in Table 12.1.
Table 12.1. Default Parser's Token Types
Alias | Description | Example |
---|---|---|
asciiword | Word, all ASCII letters | elephant |
word | Word, all letters | mañana |
numword | Word, letters and digits | beta1 |
asciihword | Hyphenated word, all ASCII | up-to-date |
hword | Hyphenated word, all letters | lógico-matemática |
numhword | Hyphenated word, letters and digits | postgresql-beta1 |
hword_asciipart | Hyphenated word part, all ASCII | postgresql in the context postgresql-beta1 |
hword_part | Hyphenated word part, all letters | lógico or matemática in the context lógico-matemática |
hword_numpart | Hyphenated word part, letters and digits | beta1 in the context postgresql-beta1 |
email | Email address | foo@example.com |
protocol | Protocol head | http:// |
url | URL | example.com/stuff/index.html |
host | Host | example.com |
url_path | URL path | /stuff/index.html , in the context of a URL |
file | File or path name | /usr/local/foo.txt , if not within a URL |
sfloat | Scientific notation | -1.234e56 |
float | Decimal notation | -1.234 |
int | Signed integer | -1234 |
uint | Unsigned integer | 1234 |
version | Version number | 8.3.0 |
tag | XML tag | <a href="/docs/postgrespro/12/dictionaries.html"> |
entity | XML entity | & |
blank | Space symbols | (any whitespace or punctuation not otherwise recognized) |
Note
The parser's notion of a “letter” is determined by the database's locale setting, specifically lc_ctype
. Words containing only the basic ASCII letters are reported as a separate token type, since it is sometimes useful to distinguish them. In most European languages, token types word
and asciiword
should be treated alike.
email
does not support all valid email characters as defined by RFC 5322. Specifically, the only non-alphanumeric characters supported for email user names are period, dash, and underscore.
It is possible for the parser to produce overlapping tokens from the same piece of text. As an example, a hyphenated word will be reported both as the entire word and as each component:
SELECT alias, description, token FROM ts_debug('foo-bar-beta1'); alias | description | token -----------------+------------------------------------------+--------------- numhword | Hyphenated word, letters and digits | foo-bar-beta1 hword_asciipart | Hyphenated word part, all ASCII | foo blank | Space symbols | - hword_asciipart | Hyphenated word part, all ASCII | bar blank | Space symbols | - hword_numpart | Hyphenated word part, letters and digits | beta1
This behavior is desirable since it allows searches to work for both the whole compound word and for components. Here is another instructive example:
SELECT alias, description, token FROM ts_debug('http://example.com/stuff/index.html'); alias | description | token ----------+---------------+------------------------------ protocol | Protocol head | http:// url | URL | example.com/stuff/index.html host | Host | example.com url_path | URL path | /stuff/index.html