F.29. ltree
Этот модуль реализует тип данных ltree для представления меток данных в иерархической древовидной структуре. Он также предоставляет расширенные средства для поиска в таких деревьях.
F.29.1. Определения
Метка — это последовательность алфавитно-цифровых символов и знаков подчёркивания (например, в локали C допускаются символы A-Za-z0-9_). Метки должны занимать меньше 256 символов.
Примеры: 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}В конце метки, отличной от звёздочки, в
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.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.29.2. Операторы и функции
Для типа ltree определены обычные операторы сравнения =, <>, <, >, <=, >=. Сравнение сортирует пути в порядке движения по дереву, а потомки узла сортируются по тексту метки. В дополнение к ним есть и специализированные операторы, перечисленные в Таблице F.19.
Таблица F.19. Операторы ltree
| Оператор | Возвращает | Описание |
|---|---|---|
ltree @> ltree | boolean | левый аргумент является предком правого (или равен ему)? |
ltree <@ ltree | boolean | левый аргумент является потомком правого (или равен ему)? |
ltree ~ lquery | boolean | значение ltree соответствует lquery? |
lquery ~ ltree | boolean | значение ltree соответствует lquery? |
ltree ? lquery[] | boolean | значение ltree соответствует одному из lquery в массиве? |
lquery[] ? ltree | boolean | значение ltree соответствует одному из lquery в массиве? |
ltree @ ltxtquery | boolean | значение ltree соответствует ltxtquery? |
ltxtquery @ ltree | boolean | значение ltree соответствует ltxtquery? |
ltree || ltree | ltree | объединяет два пути ltree |
ltree || text | ltree | преобразует текст в ltree и объединяет с путём |
text || ltree | ltree | преобразует текст в ltree и объединяет с путём |
ltree[] @> ltree | boolean | массив содержит предка ltree? |
ltree <@ ltree[] | boolean | массив содержит предка ltree? |
ltree[] <@ ltree | boolean | массив содержит потомка ltree? |
ltree @> ltree[] | boolean | массив содержит потомка ltree? |
ltree[] ~ lquery | boolean | массив содержит путь, соответствующий lquery? |
lquery ~ ltree[] | boolean | массив содержит путь, соответствующий lquery? |
ltree[] ? lquery[] | boolean | массив ltree содержит путь, соответствующий любому из lquery? |
lquery[] ? ltree[] | boolean | массив ltree содержит путь, соответствующий любому из lquery? |
ltree[] @ ltxtquery | boolean | массив содержит путь, соответствующий ltxtquery? |
ltxtquery @ ltree[] | boolean | массив содержит путь, соответствующий ltxtquery? |
ltree[] ?@> ltree | ltree | первый элемент массива, являющийся предком ltree; NULL, если такого нет |
ltree[] ?<@ ltree | ltree | первый элемент массива, являющийся потомком ltree; NULL, если такого нет |
ltree[] ?~ lquery | ltree | первый элемент массива, соответствующий lquery; NULL, если такого нет |
ltree[] ?@ ltxtquery | ltree | первый элемент массива, соответствующий ltxtquery; NULL, если такого нет |
Операторы <@, @>, @ и ~ имеют аналоги в виде ^<@, ^@>, ^@, ^~, которые отличатся только тем, что не используют индексы. Они полезны только для тестирования.
Доступные функции перечислены в Таблице F.20.
Таблица F.20. Функции ltree
F.29.3. Индексы
ltree поддерживает несколько типов индексов, которые могут ускорить означенные операции:
B-дерево по значениям
ltree:<,<=,=,>=,>GiST по значениям
ltree:<,<=,=,>=,>,@>,<@,@,~,?Пример создания такого индекса:
CREATE INDEX path_gist_idx ON test USING GIST (path);
GiST по столбцу
ltree[]:ltree[] <@ ltree,ltree @> ltree[],@,~,?Пример создания такого индекса:
CREATE INDEX path_gist_idx ON test USING GIST (array_path);
Примечание: Индекс этого типа является неточным.
F.29.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);В итоге мы получаем таблицу 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.29.5. Трансформации
Также имеются дополнительные расширения, реализующие трансформации типа ltree для языка PL/Python. Эти расширения называются ltree_plpythonu, ltree_plpython2u и ltree_plpython3u (соглашения об именовании, принятые для интерфейса PL/Python, описаны в Разделе 44.1). Если вы установите эти трансформации и укажете их при создании функции, значения ltree будут отображаться в списки Python. (Однако обратное преобразование не поддерживается.)
Внимание
Расширения, реализующие трансформации, настоятельно рекомендуется устанавливать в одну схему с ltree. Выбор какой-либо другой схемы, которая может содержать объекты, созданные злонамеренным пользователем, чреват угрозами безопасности во время установки расширения.
F.29.6. Авторы
Разработку осуществили Фёдор Сигаев (<teodor@stack.net>) и Олег Бартунов (<oleg@sai.msu.su>). Дополнительные сведения можно найти на странице http://www.sai.msu.su/~megera/postgres/gist/. Авторы выражают благодарность Евгению Родичеву за полезные дискуссии. Замечания и сообщения об ошибках приветствуются.
F.29. ltree
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.
F.29.1. Definitions
A label is a sequence of alphanumeric characters and underscores (for example, in C locale the characters A-Za-z0-9_ are allowed). Labels must be less than 256 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:
ltreestores a label path.lqueryrepresents a regular-expression-like pattern for matchingltreevalues. A simple word matches that label within a path. A star symbol (*) matches zero or more labels. 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 isfooStar symbols can also be quantified to restrict how many labels they can match:
*{n} Match exactlynlabels *{n,} Match at leastnlabels *{n,m} Match at leastnbut not more thanmlabels *{,m} Match at mostmlabels — same as *{0,m}There are several modifiers that can be put at the end of a non-star label in
lqueryto 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_bazbut notfoo_barbaz. If combined with*, prefix matching applies to each word separately, for examplefoo_bar%*matchesfoo1_bar2_bazbut notfoo1_br2_baz.Also, you can write several possibly-modified labels separated with
|(OR) to match any of those labels, and you can put!(NOT) at the start to match any label that doesn't match any of the alternatives.Here's an annotated example of
lquery:Top.*{0,2}.sport*@.!football|tennis.Russ*|Spain a. b. c. d. e.This query will match any label path that:
begins with the label
Topand next has zero to two labels before
a label beginning with the case-insensitive prefix
sportthen a label not matching
footballnortennisand then ends with a label beginning with
Russor exactly matchingSpain.
ltxtqueryrepresents a full-text-search-like pattern for matchingltreevalues. Anltxtqueryvalue 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 fromlqueryis thatltxtquerymatches 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
Europeand 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.29.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.19 are available.
Table F.19. ltree Operators
| Operator | Returns | Description |
|---|---|---|
ltree @> ltree | boolean | is left argument an ancestor of right (or equal)? |
ltree <@ ltree | boolean | is left argument a descendant of right (or equal)? |
ltree ~ lquery | boolean | does ltree match lquery? |
lquery ~ ltree | boolean | does ltree match lquery? |
ltree ? lquery[] | boolean | does ltree match any lquery in array? |
lquery[] ? ltree | boolean | does ltree match any lquery in array? |
ltree @ ltxtquery | boolean | does ltree match ltxtquery? |
ltxtquery @ ltree | boolean | does ltree match ltxtquery? |
ltree || ltree | ltree | concatenate ltree paths |
ltree || text | ltree | convert text to ltree and concatenate |
text || ltree | ltree | convert text to ltree and concatenate |
ltree[] @> ltree | boolean | does array contain an ancestor of ltree? |
ltree <@ ltree[] | boolean | does array contain an ancestor of ltree? |
ltree[] <@ ltree | boolean | does array contain a descendant of ltree? |
ltree @> ltree[] | boolean | does array contain a descendant of ltree? |
ltree[] ~ lquery | boolean | does array contain any path matching lquery? |
lquery ~ ltree[] | boolean | does array contain any path matching lquery? |
ltree[] ? lquery[] | boolean | does ltree array contain any path matching any lquery? |
lquery[] ? ltree[] | boolean | does ltree array contain any path matching any lquery? |
ltree[] @ ltxtquery | boolean | does array contain any path matching ltxtquery? |
ltxtquery @ ltree[] | boolean | does array contain any path matching ltxtquery? |
ltree[] ?@> ltree | ltree | first array entry that is an ancestor of ltree; NULL if none |
ltree[] ?<@ ltree | ltree | first array entry that is a descendant of ltree; NULL if none |
ltree[] ?~ lquery | ltree | first array entry that matches lquery; NULL if none |
ltree[] ?@ ltxtquery | ltree | first array entry that matches ltxtquery; NULL if none |
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.20.
Table F.20. ltree Functions
F.29.3. Indexes
ltree supports several types of indexes that can speed up the indicated operators:
B-tree index over
ltree:<,<=,=,>=,>GiST index over
ltree:<,<=,=,>=,>,@>,<@,@,~,?Example of creating such an index:
CREATE INDEX path_gist_idx ON test USING GIST (path);
GiST index over
ltree[]:ltree[] <@ ltree,ltree @> ltree[],@,~,?Example of creating such an index:
CREATE INDEX path_gist_idx ON test USING GIST (array_path);
Note: This index type is lossy.
F.29.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);
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 a 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.29.5. Transforms
Additional extensions are available that implement transforms for the ltree type for PL/Python. The extensions are called ltree_plpythonu, ltree_plpython2u, and ltree_plpython3u (see Section 44.1 for the PL/Python naming convention). If you install these transforms and specify them 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 extensions 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.29.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.