F.18. intarray
Модуль intarray предоставляет ряд полезных функций и операторов для работы с массивами целых чисел без NULL. Также он поддерживает поиск по индексу для некоторых из этих операторов.
Все эти операции выдают ошибку, если в передаваемом массиве оказываются значения NULL.
Многие из этих операций имеют смысл только с одномерными массивами. Хотя им можно передать входной массив и большей размерности, значения будут считываться из него как из линейного массива в порядке хранения.
F.18.1. Функции и операторы intarray
Реализованные в модуле intarray функции перечислены в Таблице F.9, а операторы — в Таблице F.10.
Таблица F.9. Функции intarray
Таблица F.10. Операторы intarray
| Оператор | Возвращает | Описание |
|---|---|---|
int[] && int[] | boolean | пересекается с — true, если массивы имеют минимум один общий элемент |
int[] @> int[] | boolean | включает — true, если левый массив содержит правый массив |
int[] <@ int[] | boolean | включается в — true, если левый массив содержится в правом массиве |
# int[] | int | число элементов в массиве |
int[] # int | int | индекс элемента (делает то же, что и функция idx) |
int[] + int | int[] | вставляет элемент в массив (добавляет его в конец массива) |
int[] + int[] | int[] | соединяет массивы (правый массив добавляется в конец левого) |
int[] - int | int[] | удаляет из массива записи, равные правому аргументу |
int[] - int[] | int[] | удаляет из левого массива элементы правого массива |
int[] | int | int[] | объединение аргументов |
int[] | int[] | int[] | объединение массивов |
int[] & int[] | int[] | пересечение массивов |
int[] @@ query_int | boolean | true, если массив удовлетворяет запросу (см. ниже) |
query_int ~~ int[] | boolean | true, если запросу удовлетворяет массив (коммутирующий оператор к @@) |
(До версии PostgreSQL 8.2 операторы включения @> и <@ обозначались соответственно как @ и ~. Эти имена по-прежнему действуют, но считаются устаревшими и в конце концов будут упразднены. Заметьте, что старые имена произошли из соглашения, которому раньше следовали ключевые геометрические типы данных!)
Операторы &&, @> и <@ равнозначны встроенным операторам PostgreSQL с теми же именами, за исключением того, что они работают только с целочисленными массивами, не содержащими NULL, тогда как встроенные операторы работают с массивами любых типов. Благодаря этому ограничению, в большинстве случаев они работают быстрее, чем встроенные операторы.
Операторы @@ и ~~ проверяют, удовлетворяет ли массив запросу, представляемому в виде значения специализированного типа данных query_int. Запрос содержит целочисленные значения, сравниваемые с элементами массива, возможно с использованием операторов & (AND), | (OR) и ! (NOT). При необходимости могут использоваться скобки. Например, запросу 1&(2|3) удовлетворяют запросы, которые содержат 1 и также содержат 2 или 3.
F.18.2. Поддержка индексов
Модуль intarray поддерживает индексы для операторов &&, @>, <@ и @@, а также обычную проверку равенства массивов.
Модуль предоставляет два класса операторов GiST: gist__int_ops (используется по умолчанию), подходящий для маленьких и средних по размеру наборов данных, и gist__intbig_ops, применяющий сигнатуру большего размера и подходящий для индексации больших наборов данных (то есть столбцов, содержащих много различных значений массива). В этой реализации используется структура данных RD-дерева со встроенным сжатием с потерями.
Есть также нестандартный класс операторов GIN, gin__int_ops, поддерживающий те же операторы.
Выбор между индексами GiST и GIN зависит от относительных характеристик производительности GiST и GIN, которые здесь не рассматриваются.
F.18.3. Пример
-- сообщение может относиться к одной или нескольким «секциям»
CREATE TABLE message (mid INT PRIMARY KEY, sections INT[], ...);
-- создать специализированный индекс
CREATE INDEX message_rdtree_idx ON message USING GIST (sections gist__int_ops);
-- вывести сообщения из секций 1 или 2 — оператор пересечения
SELECT message.mid FROM message WHERE message.sections && '{1,2}';
-- вывести сообщения из секций 1 и 2 — оператор включения
SELECT message.mid FROM message WHERE message.sections @> '{1,2}';
-- тот же результат, но с оператором запроса
SELECT message.mid FROM message WHERE message.sections @@ '1&2'::query_int;F.18.4. Тестирование производительности
В каталоге исходного кода contrib/intarray/bench содержится пакет тестов, которые можно провести на установленном сервере PostgreSQL. (Для этого нужно установить пакет DBD::Pg.) Чтобы запустить эти тесты, выполните:
cd .../contrib/intarray/bench createdb TEST psql -c "CREATE EXTENSION intarray" TEST ./create_test.pl | psql TEST ./bench.pl
Скрипт bench.pl принимает несколько аргументов, о которых можно узнать, запустив его без аргументов.
F.18.5. Авторы
Разработку осуществили Фёдор Сигаев (<teodor@sigaev.ru>) и Олег Бартунов (<oleg@sai.msu.su>). Дополнительные сведения можно найти на странице http://www.sai.msu.su/~megera/postgres/gist/. Андрей Октябрьский проделал отличную работу, добавив новые функции и операторы.
F.18. intarray
The intarray module provides a number of useful functions and operators for manipulating null-free arrays of integers. There is also support for indexed searches using some of the operators.
All of these operations will throw an error if a supplied array contains any NULL elements.
Many of these operations are only sensible for one-dimensional arrays. Although they will accept input arrays of more dimensions, the data is treated as though it were a linear array in storage order.
F.18.1. intarray Functions and Operators
The functions provided by the intarray module are shown in Table F.9, the operators in Table F.10.
Table F.9. intarray Functions
Table F.10. intarray Operators
| Operator | Returns | Description |
|---|---|---|
int[] && int[] | boolean | overlap — true if arrays have at least one common element |
int[] @> int[] | boolean | contains — true if left array contains right array |
int[] <@ int[] | boolean | contained — true if left array is contained in right array |
# int[] | int | number of elements in array |
int[] # int | int | index (same as idx function) |
int[] + int | int[] | push element onto array (add it to end of array) |
int[] + int[] | int[] | array concatenation (right array added to the end of left one) |
int[] - int | int[] | remove entries matching right argument from array |
int[] - int[] | int[] | remove elements of right array from left |
int[] | int | int[] | union of arguments |
int[] | int[] | int[] | union of arrays |
int[] & int[] | int[] | intersection of arrays |
int[] @@ query_int | boolean | true if array satisfies query (see below) |
query_int ~~ int[] | boolean | true if array satisfies query (commutator of @@) |
(Before PostgreSQL 8.2, the containment operators @> and <@ were respectively called @ and ~. These names are still available, but are deprecated and will eventually be retired. Notice that the old names are reversed from the convention formerly followed by the core geometric data types!)
The operators &&, @> and <@ are equivalent to PostgreSQL's built-in operators of the same names, except that they work only on integer arrays that do not contain nulls, while the built-in operators work for any array type. This restriction makes them faster than the built-in operators in many cases.
The @@ and ~~ operators test whether an array satisfies a query, which is expressed as a value of a specialized data type query_int. A query consists of integer values that are checked against the elements of the array, possibly combined using the operators & (AND), | (OR), and ! (NOT). Parentheses can be used as needed. For example, the query 1&(2|3) matches arrays that contain 1 and also contain either 2 or 3.
F.18.2. Index Support
intarray provides index support for the &&, @>, <@, and @@ operators, as well as regular array equality.
Two GiST index operator classes are provided: gist__int_ops (used by default) is suitable for small- to medium-size data sets, while gist__intbig_ops uses a larger signature and is more suitable for indexing large data sets (i.e., columns containing a large number of distinct array values). The implementation uses an RD-tree data structure with built-in lossy compression.
There is also a non-default GIN operator class gin__int_ops supporting the same operators.
The choice between GiST and GIN indexing depends on the relative performance characteristics of GiST and GIN, which are discussed elsewhere.
F.18.3. Example
-- a message can be in one or more “sections”
CREATE TABLE message (mid INT PRIMARY KEY, sections INT[], ...);
-- create specialized index
CREATE INDEX message_rdtree_idx ON message USING GIST (sections gist__int_ops);
-- select messages in section 1 OR 2 - OVERLAP operator
SELECT message.mid FROM message WHERE message.sections && '{1,2}';
-- select messages in sections 1 AND 2 - CONTAINS operator
SELECT message.mid FROM message WHERE message.sections @> '{1,2}';
-- the same, using QUERY operator
SELECT message.mid FROM message WHERE message.sections @@ '1&2'::query_int;
F.18.4. Benchmark
The source directory contrib/intarray/bench contains a benchmark test suite, which can be run against an installed PostgreSQL server. (It also requires DBD::Pg to be installed.) To run:
cd .../contrib/intarray/bench createdb TEST psql -c "CREATE EXTENSION intarray" TEST ./create_test.pl | psql TEST ./bench.pl
The bench.pl script has numerous options, which are displayed when it is run without any arguments.
F.18.5. Authors
All work was done by Teodor Sigaev (<teodor@sigaev.ru>) and Oleg Bartunov (<oleg@sai.msu.su>). See http://www.sai.msu.su/~megera/postgres/gist/ for additional information. Andrey Oktyabrski did a great work on adding new functions and operations.