F.30. ltree — тип данных для представления меток данных в иерархической древовидной структуре #
Этот модуль реализует тип данных ltree
для представления меток данных в иерархической древовидной структуре. Он также предоставляет расширенные средства для поиска в таких деревьях.
Данный модуль считается «доверенным», то есть его могут устанавливать обычные пользователи, имеющие право CREATE
в текущей базе данных.
F.30.1. Определения #
Метка — это последовательность буквенно-цифровых символов, знаков подчёркивания и дефисов. Допустимые диапазоны буквенно-цифровых символов зависят от локали базы данных. Например, в локали C допускаются символы A-Za-z0-9_-
. Метки должны занимать меньше 1000 символов.
Примеры: 42
, Personal_Services
Путь метки — это последовательность из нуля или нескольких разделённых точками меток (например, L1.L2.L3
), представляющая путь от корня иерархического дерева к конкретному узлу. Путь не может содержать больше 65535 меток.
Пример: Top.Countries.Europe.Russia
Модуль ltree
предоставляет несколько типов данных:
ltree
хранит путь метки.lquery
представляет напоминающий регулярные выражения запрос для поиска нужных значенийltree
. В нём простое слово выбирает соответствующую метку в заданном пути, а звёздочка (*
) — ноль или более любых меток. Отдельные компоненты можно соединить точками и получить запрос, которому будет соответствовать весь путь с указанными метками. Например:foo Выбирает путь ровно с одной меткой
foo
*.foo.* Выбирает путь, содержащий меткуfoo
*.foo Выбирает путь с последней меткойfoo
И для звёздочки, и для простых слов можно добавить количественное значение, определяющее число меток, которые будут соответствовать этому компоненту:
*{
n
} Выбирает ровноn
меток *{n
,} Выбирает как минимумn
меток *{n
,m
} Выбирает не меньшеn
, но и не болееm
меток *{,m
} Выбирает не большеm
меток — равнозначно *{0,m
} foo{n
,m
} Выбирает как минимумn
, но не большеm
вхожденийfoo
foo{,} Выбирает любое количество вхожденийfoo
, в том числе нольВ отсутствие явного числового ограничения символу звёздочки по умолчанию соответствует любое количество меток (то есть
{,}
), а обычному слову — ровно одно вхождение (то есть{1}
).После отличного от звёздочки элемента
lquery
могут быть добавлены модификаторы, позволяющие выбрать не только простые совпадения:@ Выбирает совпадение без учёта регистра; например, запросу
a@
соответствуетA
* Выбирает любую метку с заданным префиксом, например, запросуfoo*
соответствуетfoobar
% Выбирает в метке начальные слова, разделённые подчёркиваниямиПоведение модификатора
%
несколько нетривиальное. Он пытается найти соответствие по словам, а не по всей метке. Например, запросfoo_bar%
выбираетfoo_bar_baz
, но неfoo_barbaz
. В сочетании с*
сопоставление префикса применяется отдельно к каждому слову, например запросfoo_bar%*
выбираетfoo1_bar2_baz
, но неfoo1_br2_baz
.Также можно записать несколько различных меток, отличных от звёздочек, через знак
|
(обозначающий ИЛИ) для выбора любой из этих меток, либо добавить знак!
(НЕ) в начале группы без звёздочки для выбора метки, не соответствующей ни одной из указанных альтернатив. Количественное ограничение, если оно требуется, задаётся в конце группы; это означает, что оно действует на всю группу в целом (то есть ограничивает число меток, соответствующих или не соответствующих одной из альтернатив).Расширенный пример
lquery
:Top.*{0,2}.sport*@.!football|tennis{1,}.Russ*|Spain a. b. c. d. e.
Этот запрос выберет путь, который:
начинается с метки
Top
и затем включает от нуля до двух меток до
метки, начинающейся с префикса
sport
(без учёта регистра)затем одну или несколько меток, отличных от
football
иtennis
и заканчивается меткой, которая начинается подстрокой
Russ
или в точности равнаSpain
.
ltxtquery
представляет подобный полнотекстовому запрос поиска подходящих значенийltree
. Значениеltxtquery
содержит слова, возможно с модификаторами@
,*
,%
в конце; эти модификаторы имеют то же значение, что и вlquery
. Слова можно объединять символами&
(И),|
(ИЛИ),!
(НЕ) и скобками. Ключевое отличие отlquery
состоит в том, чтоltxtquery
выбирает слова независимо от их положения в пути метки.Пример
ltxtquery
:Europe & Russia*@ & !Transportation
Этот запрос выберет пути, содержащие метку
Europe
или любую метку с начальной подстрокойRussia
(без учёта регистра), но не пути, содержащие меткуTransportation
. Положение этих слов в пути не имеет значения. Кроме того, когда применяется%
, слово может быть сопоставлено с любым другим отделённым подчёркиваниями словом в метке, вне зависимости от его положения.
Замечание: ltxtquery
допускает пробелы между символами, а ltree
и lquery
— нет.
F.30.2. Операторы и функции #
Для типа ltree
определены обычные операторы сравнения =
, <>
, <
, >
, <=
, >=
. Сравнение сортирует пути в порядке движения по дереву, а потомки узла сортируются по тексту метки. В дополнение к ним есть и специализированные операторы, перечисленные в Таблице F.17.
Таблица F.17. Операторы ltree
Оператор Описание |
---|
Левый аргумент является предком правого (или равен ему)? |
Левый аргумент является потомком правого (или равен ему)? |
Значение |
Значение |
Значение |
Соединяет два пути |
Преобразует текст в |
Массив содержит предка |
Массив содержит потомка |
Массив содержит какой-либо путь, соответствующий |
Массив |
Массив содержит путь, соответствующий |
Выдаёт первый элемент массива, являющийся предком |
Выдаёт первый элемент массива, являющийся потомком |
Выдаёт первый элемент массива, соответствующий |
Выдаёт первый элемент массива, соответствующий |
Операторы <@
, @>
, @
и ~
имеют аналоги в виде ^<@
, ^@>
, ^@
, ^~
, которые отличатся только тем, что не используют индексы. Они полезны только для тестирования.
Доступные функции перечислены в Таблице F.18.
Таблица F.18. Функции ltree
F.30.3. Индексы #
ltree
поддерживает несколько типов индексов, которые могут ускорить означенные операции:
B-дерево по значениям
ltree
:<
,<=
,=
,>=
,>
Хеш-индекс по значениям
ltree
:=
GiST по значениям
ltree
(класс операторовgist_ltree_ops
):<
,<=
,=
,>=
,>
,@>
,<@
,@
,~
,?
Класс операторов GiST
gist_ltree_ops
аппроксимирует набор меток пути в виде сигнатуры битовой карты. В его необязательном целочисленном параметреsiglen
можно задать размер сигнатуры в байтах. Размер сигнатуры по умолчанию — 8 байт. Параметр может принимать положительные значения до 2024, кратные выравниванию по целым (int
) (4 байта для большинства машин). При увеличении размера сигнатуры поиск работает точнее (сканируется меньшая область в индексе и меньше страниц кучи), но сам индекс становится больше.Пример создания такого индекса с размером сигнатуры по умолчанию (8 байт):
CREATE INDEX path_gist_idx ON test USING GIST (path);
Пример создания такого индекса с длиной сигнатуры 100 байт:
CREATE INDEX path_gist_idx ON test USING GIST (path gist_ltree_ops(siglen=100));
GiST-индекс по массиву
ltree[]
(gist__ltree_ops
opclass):ltree[] <@ ltree
,ltree @> ltree[]
,@
,~
,?
Класс операторов GiST
gist__ltree_ops
работает подобноgist_ltree_ops
и также принимает в параметре длину сигнатуры. По умолчанию значениеsiglen
вgist__ltree_ops
составляет 28 байт.Пример создания такого индекса с размером сигнатуры по умолчанию (28 байт):
CREATE INDEX path_gist_idx ON test USING GIST (array_path);
Пример создания такого индекса с длиной сигнатуры 100 байт:
CREATE INDEX path_gist_idx ON test USING GIST (array_path gist__ltree_ops(siglen=100));
Примечание: Индекс этого типа является неточным.
F.30.4. Пример #
Для этого примера используются следующие данные (это же описание данных находится в файле contrib/ltree/ltreetest.sql
в дистрибутиве исходного кода):
CREATE TABLE test (path ltree); INSERT INTO test VALUES ('Top'); INSERT INTO test VALUES ('Top.Science'); INSERT INTO test VALUES ('Top.Science.Astronomy'); INSERT INTO test VALUES ('Top.Science.Astronomy.Astrophysics'); INSERT INTO test VALUES ('Top.Science.Astronomy.Cosmology'); INSERT INTO test VALUES ('Top.Hobbies'); INSERT INTO test VALUES ('Top.Hobbies.Amateurs_Astronomy'); INSERT INTO test VALUES ('Top.Collections'); INSERT INTO test VALUES ('Top.Collections.Pictures'); INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy'); INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Stars'); INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Galaxies'); INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Astronauts'); CREATE INDEX path_gist_idx ON test USING GIST (path); CREATE INDEX path_idx ON test USING BTREE (path); CREATE INDEX path_hash_idx ON test USING HASH (path);
В итоге мы получаем таблицу test
, наполненную данными, представляющими следующую иерархию:
Top / | \ Science Hobbies Collections / | \ Astronomy Amateurs_Astronomy Pictures / \ | Astrophysics Cosmology Astronomy / | \ Galaxies Stars Astronauts
Мы можем выбрать потомки в иерархии наследования:
ltreetest=> SELECT path FROM test WHERE path <@ 'Top.Science'; path ------------------------------------ Top.Science Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology (4 rows)
Несколько примеров выборки по путям:
ltreetest=> SELECT path FROM test WHERE path ~ '*.Astronomy.*'; path ----------------------------------------------- Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology Top.Collections.Pictures.Astronomy Top.Collections.Pictures.Astronomy.Stars Top.Collections.Pictures.Astronomy.Galaxies Top.Collections.Pictures.Astronomy.Astronauts (7 rows) ltreetest=> SELECT path FROM test WHERE path ~ '*.!pictures@.Astronomy.*'; path ------------------------------------ Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology (3 rows)
Ещё несколько примеров полнотекстового поиска:
ltreetest=> SELECT path FROM test WHERE path @ 'Astro*% & !pictures@'; path ------------------------------------ Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology Top.Hobbies.Amateurs_Astronomy (4 rows) ltreetest=> SELECT path FROM test WHERE path @ 'Astro* & !pictures@'; path ------------------------------------ Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology (3 rows)
Образование пути с помощью функций:
ltreetest=> SELECT subpath(path,0,2)||'Space'||subpath(path,2) FROM test WHERE path <@ 'Top.Science.Astronomy'; ?column? ------------------------------------------ Top.Science.Space.Astronomy Top.Science.Space.Astronomy.Astrophysics Top.Science.Space.Astronomy.Cosmology (3 rows)
Эту процедуру можно упростить, создав функцию SQL, вставляющую метку в определённую позицию в пути:
CREATE FUNCTION ins_label(ltree, int, text) RETURNS ltree AS 'select subpath($1,0,$2) || $3 || subpath($1,$2);' LANGUAGE SQL IMMUTABLE; ltreetest=> SELECT ins_label(path,2,'Space') FROM test WHERE path <@ 'Top.Science.Astronomy'; ins_label ------------------------------------------ Top.Science.Space.Astronomy Top.Science.Space.Astronomy.Astrophysics Top.Science.Space.Astronomy.Cosmology (3 rows)
F.30.5. Трансформации #
Расширение ltree_plpython3u
реализует трансформации типа ltree
для языка PL/Python. Если вы установите эти трансформации и укажете их при создании функции, значения ltree
будут отображаться в списки Python. (Однако обратное преобразование не поддерживается.)
Внимание
Расширение, реализующее трансформации, настоятельно рекомендуется устанавливать в одну схему с ltree
. Выбор какой-либо другой схемы, которая может содержать объекты, созданные злонамеренным пользователем, чреват угрозами безопасности во время установки расширения.
F.30.6. Авторы #
Разработку осуществили Фёдор Сигаев (<teodor@stack.net>
) и Олег Бартунов (<oleg@sai.msu.su>
). Дополнительные сведения можно найти на странице http://www.sai.msu.su/~megera/postgres/gist/. Авторы выражают благодарность Евгению Родичеву за полезные дискуссии. Замечания и сообщения об ошибках приветствуются.
F.30. ltree — hierarchical tree-like data type #
This module implements a data type ltree
for representing labels of data stored in a hierarchical tree-like structure. Extensive facilities for searching through label trees are provided.
This module is considered “trusted”, that is, it can be installed by non-superusers who have CREATE
privilege on the current database.
F.30.1. Definitions #
A label is a sequence of alphanumeric characters, underscores, and hyphens. Valid alphanumeric character ranges are dependent on the database locale. For example, in C locale, the characters A-Za-z0-9_-
are allowed. Labels must be no more than 1000 characters long.
Examples: 42
, Personal_Services
A label path is a sequence of zero or more labels separated by dots, for example L1.L2.L3
, representing a path from the root of a hierarchical tree to a particular node. The length of a label path cannot exceed 65535 labels.
Example: Top.Countries.Europe.Russia
The ltree
module provides several data types:
ltree
stores a label path.lquery
represents a regular-expression-like pattern for matchingltree
values. A simple word matches that label within a path. A star symbol (*
) matches zero or more labels. These can be joined with dots to form a pattern that must match the whole label path. For example:foo Match the exact label path
foo
*.foo.* Match any label path containing the labelfoo
*.foo Match any label path whose last label isfoo
Both star symbols and simple words can be quantified to restrict how many labels they can match:
*{
n
} Match exactlyn
labels *{n
,} Match at leastn
labels *{n
,m
} Match at leastn
but not more thanm
labels *{,m
} Match at mostm
labels — same as *{0,m
} foo{n
,m
} Match at leastn
but not more thanm
occurrences offoo
foo{,} Match any number of occurrences offoo
, including zeroIn the absence of any explicit quantifier, the default for a star symbol is to match any number of labels (that is,
{,}
) while the default for a non-star item is to match exactly once (that is,{1}
).There are several modifiers that can be put at the end of a non-star
lquery
item to make it match more than just the exact match:@ Match case-insensitively, for example
a@
matchesA
* Match any label with this prefix, for examplefoo*
matchesfoobar
% Match initial underscore-separated wordsThe behavior of
%
is a bit complicated. It tries to match words rather than the entire label. For examplefoo_bar%
matchesfoo_bar_baz
but notfoo_barbaz
. If combined with*
, prefix matching applies to each word separately, for examplefoo_bar%*
matchesfoo1_bar2_baz
but notfoo1_br2_baz
.Also, you can write several possibly-modified non-star items separated with
|
(OR) to match any of those items, and you can put!
(NOT) at the start of a non-star group to match any label that doesn't match any of the alternatives. A quantifier, if any, goes at the end of the group; it means some number of matches for the group as a whole (that is, some number of labels matching or not matching any of the alternatives).Here's an annotated example of
lquery
:Top.*{0,2}.sport*@.!football|tennis{1,}.Russ*|Spain a. b. c. d. e.
This query will match any label path that:
begins with the label
Top
and next has zero to two labels before
a label beginning with the case-insensitive prefix
sport
then has one or more labels, none of which match
football
nortennis
and then ends with a label beginning with
Russ
or exactly matchingSpain
.
ltxtquery
represents a full-text-search-like pattern for matchingltree
values. Anltxtquery
value contains words, possibly with the modifiers@
,*
,%
at the end; the modifiers have the same meanings as inlquery
. Words can be combined with&
(AND),|
(OR),!
(NOT), and parentheses. The key difference fromlquery
is thatltxtquery
matches words without regard to their position in the label path.Here's an example
ltxtquery
:Europe & Russia*@ & !Transportation
This will match paths that contain the label
Europe
and any label beginning withRussia
(case-insensitive), but not paths containing the labelTransportation
. The location of these words within the path is not important. Also, when%
is used, the word can be matched to any underscore-separated word within a label, regardless of position.
Note: ltxtquery
allows whitespace between symbols, but ltree
and lquery
do not.
F.30.2. Operators and Functions #
Type ltree
has the usual comparison operators =
, <>
, <
, >
, <=
, >=
. Comparison sorts in the order of a tree traversal, with the children of a node sorted by label text. In addition, the specialized operators shown in Table F.17 are available.
Table F.17. ltree
Operators
Operator Description |
---|
Is left argument an ancestor of right (or equal)? |
Is left argument a descendant of right (or equal)? |
Does |
Does |
Does |
Concatenates |
Converts text to |
Does array contain an ancestor of |
Does array contain a descendant of |
Does array contain any path matching |
Does |
Does array contain any path matching |
Returns first array entry that is an ancestor of |
Returns first array entry that is a descendant of |
Returns first array entry that matches |
Returns first array entry that matches |
The operators <@
, @>
, @
and ~
have analogues ^<@
, ^@>
, ^@
, ^~
, which are the same except they do not use indexes. These are useful only for testing purposes.
The available functions are shown in Table F.18.
Table F.18. ltree
Functions
F.30.3. Indexes #
ltree
supports several types of indexes that can speed up the indicated operators:
B-tree index over
ltree
:<
,<=
,=
,>=
,>
Hash index over
ltree
:=
GiST index over
ltree
(gist_ltree_ops
opclass):<
,<=
,=
,>=
,>
,@>
,<@
,@
,~
,?
gist_ltree_ops
GiST opclass approximates a set of path labels as a bitmap signature. Its optional integer parametersiglen
determines the signature length in bytes. The default signature length is 8 bytes. The length must be a positive multiple ofint
alignment (4 bytes on most machines)) up to 2024. Longer signatures lead to a more precise search (scanning a smaller fraction of the index and fewer heap pages), at the cost of a larger index.Example of creating such an index with the default signature length of 8 bytes:
CREATE INDEX path_gist_idx ON test USING GIST (path);
Example of creating such an index with a signature length of 100 bytes:
CREATE INDEX path_gist_idx ON test USING GIST (path gist_ltree_ops(siglen=100));
GiST index over
ltree[]
(gist__ltree_ops
opclass):ltree[] <@ ltree
,ltree @> ltree[]
,@
,~
,?
gist__ltree_ops
GiST opclass works similarly togist_ltree_ops
and also takes signature length as a parameter. The default value ofsiglen
ingist__ltree_ops
is 28 bytes.Example of creating such an index with the default signature length of 28 bytes:
CREATE INDEX path_gist_idx ON test USING GIST (array_path);
Example of creating such an index with a signature length of 100 bytes:
CREATE INDEX path_gist_idx ON test USING GIST (array_path gist__ltree_ops(siglen=100));
Note: This index type is lossy.
F.30.4. Example #
This example uses the following data (also available in file contrib/ltree/ltreetest.sql
in the source distribution):
CREATE TABLE test (path ltree); INSERT INTO test VALUES ('Top'); INSERT INTO test VALUES ('Top.Science'); INSERT INTO test VALUES ('Top.Science.Astronomy'); INSERT INTO test VALUES ('Top.Science.Astronomy.Astrophysics'); INSERT INTO test VALUES ('Top.Science.Astronomy.Cosmology'); INSERT INTO test VALUES ('Top.Hobbies'); INSERT INTO test VALUES ('Top.Hobbies.Amateurs_Astronomy'); INSERT INTO test VALUES ('Top.Collections'); INSERT INTO test VALUES ('Top.Collections.Pictures'); INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy'); INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Stars'); INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Galaxies'); INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Astronauts'); CREATE INDEX path_gist_idx ON test USING GIST (path); CREATE INDEX path_idx ON test USING BTREE (path); CREATE INDEX path_hash_idx ON test USING HASH (path);
Now, we have a table test
populated with data describing the hierarchy shown below:
Top / | \ Science Hobbies Collections / | \ Astronomy Amateurs_Astronomy Pictures / \ | Astrophysics Cosmology Astronomy / | \ Galaxies Stars Astronauts
We can do inheritance:
ltreetest=> SELECT path FROM test WHERE path <@ 'Top.Science'; path ------------------------------------ Top.Science Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology (4 rows)
Here are some examples of path matching:
ltreetest=> SELECT path FROM test WHERE path ~ '*.Astronomy.*'; path ----------------------------------------------- Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology Top.Collections.Pictures.Astronomy Top.Collections.Pictures.Astronomy.Stars Top.Collections.Pictures.Astronomy.Galaxies Top.Collections.Pictures.Astronomy.Astronauts (7 rows) ltreetest=> SELECT path FROM test WHERE path ~ '*.!pictures@.Astronomy.*'; path ------------------------------------ Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology (3 rows)
Here are some examples of full text search:
ltreetest=> SELECT path FROM test WHERE path @ 'Astro*% & !pictures@'; path ------------------------------------ Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology Top.Hobbies.Amateurs_Astronomy (4 rows) ltreetest=> SELECT path FROM test WHERE path @ 'Astro* & !pictures@'; path ------------------------------------ Top.Science.Astronomy Top.Science.Astronomy.Astrophysics Top.Science.Astronomy.Cosmology (3 rows)
Path construction using functions:
ltreetest=> SELECT subpath(path,0,2)||'Space'||subpath(path,2) FROM test WHERE path <@ 'Top.Science.Astronomy'; ?column? ------------------------------------------ Top.Science.Space.Astronomy Top.Science.Space.Astronomy.Astrophysics Top.Science.Space.Astronomy.Cosmology (3 rows)
We could simplify this by creating an SQL function that inserts a label at a specified position in a path:
CREATE FUNCTION ins_label(ltree, int, text) RETURNS ltree AS 'select subpath($1,0,$2) || $3 || subpath($1,$2);' LANGUAGE SQL IMMUTABLE; ltreetest=> SELECT ins_label(path,2,'Space') FROM test WHERE path <@ 'Top.Science.Astronomy'; ins_label ------------------------------------------ Top.Science.Space.Astronomy Top.Science.Space.Astronomy.Astrophysics Top.Science.Space.Astronomy.Cosmology (3 rows)
F.30.5. Transforms #
The ltree_plpython3u
extension implements transforms for the ltree
type for PL/Python. If installed and specified when creating a function, ltree
values are mapped to Python lists. (The reverse is currently not supported, however.)
Caution
It is strongly recommended that the transform extension be installed in the same schema as ltree
. Otherwise there are installation-time security hazards if a transform extension's schema contains objects defined by a hostile user.
F.30.6. Authors #
All work was done by Teodor Sigaev (<teodor@stack.net>
) and Oleg Bartunov (<oleg@sai.msu.su>
). See http://www.sai.msu.su/~megera/postgres/gist/ for additional information. Authors would like to thank Eugeny Rodichev for helpful discussions. Comments and bug reports are welcome.