67.4. Индексы GIN #
67.4.1. Введение #
GIN расшифровывается как «Generalized Inverted Index» (Обобщённый инвертированный индекс). GIN предназначается для случаев, когда индексируемые значения являются составными, а запросы, на обработку которых рассчитан индекс, ищут значения элементов в этих составных объектах. Например, такими объектами могут быть документы, а запросы могут выполнять поиск документов, содержащих определённые слова.
Здесь мы используем термин объект, говоря о составном значении, которое индексируется, и термин ключ, говоря о включённом в него элементе. GIN всегда хранит и ищет ключи, а не объекты как таковые.
Индекс GIN сохраняет набор пар (ключ, список идентификаторов), где список идентификаторов содержит идентификаторы строк, в которых находится ключ. Один и тот же идентификатор строки может фигурировать в нескольких списках, так как объект может содержать больше одного ключа. Значение каждого ключа хранится только один раз, так что индекс GIN очень компактен в случаях, когда один ключ встречается много раз.
GIN является обобщённым в том смысле, что код метода доступа GIN не должен знать о конкретных операциях, которые он ускоряет. Вместо этого задаются специальные стратегии для конкретных типов данных. Стратегия определяет, как извлекаются ключи из индексируемых объектов и условий запросов, и как установить, действительно ли удовлетворяет запросу строка, содержащая некоторые значения ключей.
Ключевым преимуществом GIN является то, что он позволяет разрабатывать дополнительные типы данных с соответствующими методами доступа экспертам в предметной области типа данных, а не специалистам по СУБД. В этом аспекте он похож на GiST.
Сопровождением реализации GIN в Postgres Pro в основном занимаются Фёдор Сигаев и Олег Бартунов. Дополнительные сведения о GIN можно получить на их сайте.
67.4.2. Встроенные классы операторов #
В базовый дистрибутив Postgres Pro включены классы операторов GIN, перечисленные в Таблице 67.3. (Некоторые дополнительные модули, описанные в Приложении F, добавляют другие классы операторов GIN.)
Таблица 67.3. Встроенные классы операторов GIN
| Имя | Индексируемые операторы |
|---|---|
array_ops | && (anyarray,anyarray) |
@> (anyarray,anyarray) | |
<@ (anyarray,anyarray) | |
= (anyarray,anyarray) | |
jsonb_ops | @> (jsonb,jsonb) |
@? (jsonb,jsonpath) | |
@@ (jsonb,jsonpath) | |
? (jsonb,text) | |
?| (jsonb,text[]) | |
?& (jsonb,text[]) | |
jsonb_path_ops | @> (jsonb,jsonb) |
@? (jsonb,jsonpath) | |
@@ (jsonb,jsonpath) | |
tsvector_ops | @@ (tsvector,tsquery) |
Из двух классов операторов для типа jsonb классом по умолчанию является jsonb_ops. Класс jsonb_path_ops поддерживает меньше операторов, но обеспечивает для них большую производительность. За подробностями обратитесь к Подразделу 8.14.4.
67.4.3. Расширяемость #
Интерфейс GIN характеризуется высоким уровнем абстракции и таким образом требует от разработчика метода доступа реализовать только смысловое наполнение обрабатываемого типа данных. Уровень GIN берёт на себя заботу о параллельном доступе, поддержке журнала и поиске в структуре дерева.
Всё, что нужно, чтобы получить работающий метод доступа GIN — это реализовать несколько пользовательских методов, определяющих поведение ключей в дереве и отношения между ключами, индексируемыми объектами и поддерживаемыми запросами. Словом, GIN сочетает расширяемость с универсальностью, повторным использованием кода и аккуратным интерфейсом.
Класс операторов должен предоставить GIN следующие два метода:
Datum *extractValue(Datum itemValue, int32 *nkeys, bool **nullFlags)Возвращает массив ключей (выделенный через palloc) для индексируемого объекта. Число возвращаемых ключей должно записываться в
*nkeys. Если какой-либо из ключей может быть NULL, нужно так же выделить через palloc массив из*nkeysполейbool, записать его адрес в*nullFlagsи установить эти флаги NULL как требуется. В*nullFlagsможно оставить значениеNULL(это начальное значение), если все ключи отличны от NULL. Эта функция может возвратитьNULL, если объект не содержит ключей.Datum *extractQuery(Datum query, int32 *nkeys, StrategyNumber n, bool **pmatch, Pointer **extra_data, bool **nullFlags, int32 *searchMode)Возвращает массив ключей (выделенный через palloc) для запрашиваемого значения; то есть, в
queryпоступает значение, находящееся по правую сторону индексируемого оператора, по левую сторону которого указан индексируемый столбец. Аргументnзадаёт номер стратегии оператора в классе операторов (см. Подраздел 40.16.2). Часто функцияextractQueryдолжна проанализироватьn, чтобы определить тип данных аргументаqueryи выбрать метод для извлечения значений ключей. Число возвращаемых ключей должно быть записано в*nkeys. Если какие-либо ключи могут быть NULL, нужно так же выделить через palloc массив из*nkeysполейbool, сохранить его адрес в*nullFlags, и установить эти флаги NULL как требуется. В*nullFlagsможно оставить значениеNULL(это начальное значение), если все ключи отличны от NULL. Эта функция может возвратитьNULL, еслиqueryне содержит ключей.Выходной аргумент
searchModeпозволяет функцииextractQueryвыбрать режим, в котором должен выполняться поиск. Если*searchModeимеет значениеGIN_SEARCH_MODE_DEFAULT(это значение устанавливается перед вызовом), подходящими кандидатами считаются только те объекты, которые соответствуют минимум одному из возвращённых ключей. Если в*searchModeустановлено значениеGIN_SEARCH_MODE_INCLUDE_EMPTY, то в дополнение к объектам с минимум одним совпадением ключа, подходящими кандидатами будут считаться и объекты, вообще не содержащие ключей. (Этот режим полезен для реализации, например, операторов A-является-подмножеством-B.) Если в*searchModeустановлено значениеGIN_SEARCH_MODE_ALL, подходящими кандидатами считаются все отличные от NULL объекты в индексе, независимо от того, встречаются ли в них возвращаемые ключи. (Этот режим намного медленнее двух других, так как он по сути требует сканирования всего индекса, но он может быть необходим для корректной обработки крайних случаев. Оператор, который выбирает этот режим в большинстве ситуаций, скорее всего не подходит для реализации в классе операторов GIN.) Символы для этих значений режима определены вaccess/gin.h.Выходной аргумент
pmatchиспользуется, когда поддерживается частичное соответствие. Чтобы использовать его,extractQueryдолжна выделить массив из*nkeysлогических элементов и сохранить его адрес в*pmatch. Элемент этого массива должен содержать true, если соответствующий ключ требует частичного соответствия, и false в противном случае. Если переменная*pmatchсодержитNULL, GIN полагает, что частичное соответствие не требуется. В эту переменную записываетсяNULLперед вызовом, так что этот аргумент можно просто игнорировать в классах операторов, не поддерживающих частичное соответствие.Выходной аргумент
extra_dataпозволяет функцииextractQueryпередать дополнительные данные методамconsistentиcomparePartial. Чтобы использовать его,extractQueryдолжна выделить массив из*nkeysуказателей и сохранить его адрес в*extra_data, а затем сохранить всё, что ей требуется, в отдельных указателях. В эту переменную записываетсяNULLперед вызовом, поэтому данный аргумент может просто игнорироваться классами операторов, которым не нужны дополнительные данные. Если массив*extra_dataзадан, он целиком передаётся в методconsistent, а вcomparePartialпередаётся соответствующий его элемент.
Класс операторов должен также предоставить функцию для проверки, соответствует ли индексированный объект запросу. Поддерживаются две её вариации: булева consistent и троичная triConsistent. Функция triConsistent покрывает функциональность обоих, так что достаточно реализовать только её. Однако если вычисление булевой вариации оказывается значительно дешевле, может иметь смысл реализовать их обе. Если представлена только булева вариация, некоторые оптимизации, построенные на отбраковывании объектов до выборки всех ключей, отключаются.
bool consistent(bool check[], StrategyNumber n, Datum query, int32 nkeys, Pointer extra_data[], bool *recheck, Datum queryKeys[], bool nullFlags[])Возвращает true, если индексированный объект удовлетворяет оператору запроса с номером стратегии
n(или потенциально удовлетворяет, когда возвращается указание перепроверки). Эта функция не имеет прямого доступа к значению индексированного объекта, так как GIN не хранит сами объекты. Вместо этого, она знает о значениях ключей, извлечённых из запроса и встречающихся в данном индексированном объекте. Массивcheckимеет длинуnkeys, что равняется числу ключей, ранее возвращённых функциейextractQueryдля данного значенияquery. Элемент массиваcheckравняется true, если индексированный объект содержит соответствующий ключ запроса; то есть, если (check[i] == true), то i-й ключ в массиве результатаextractQueryприсутствует в индексированном объекте. Исходное значениеqueryпередаётся на случай, если оно потребуется методуconsistent; с той же целью ему передаются массивыqueryKeys[]иnullFlags[], ранее возвращённые функциейextractQuery. В аргументеextra_dataпередаётся массив дополнительных данных, возвращённый функциейextractQuery, илиNULL, если дополнительных данных нет.Когда
extractQueryвозвращает ключ NULL вqueryKeys[], соответствующий элементcheck[]содержит true, если индексированный объект содержит ключ NULL; то есть можно считать, что элементыcheck[]отражают условиеIS NOT DISTINCT FROM. Функцияconsistentможет проверить соответствующий элементnullFlags[], если ей нужно различать соответствие с обычным значением и соответствие с NULL.В случае успеха в
*recheckнужно записать true, если кортеж данных нужно перепроверить с оператором запроса, либо false, если проверка по индексу была точной. То есть результат false гарантирует, что кортеж данных не соответствует запросу; результат true со значением*recheck, равным false, гарантирует, что кортеж данных соответствует запросу; а результат true со значением*recheck, равным true, означает, что кортеж данных может соответствовать запросу, поэтому его нужно выбрать и перепроверить, применив оператор запроса непосредственно к исходному индексированному элементу.GinTernaryValue triConsistent(GinTernaryValue check[], StrategyNumber n, Datum query, int32 nkeys, Pointer extra_data[], Datum queryKeys[], bool nullFlags[])Функция
triConsistentподобнаconsistent, но вместо булевых значений в вектореcheckей передаются три варианта сравнений для каждого ключа:GIN_TRUE,GIN_FALSEиGIN_MAYBE.GIN_FALSEиGIN_TRUEимеют обычное логическое значение, тогда какGIN_MAYBEозначает, что присутствие ключа неизвестно. Когда присутствуют значенияGIN_MAYBE, функция должна возвращатьGIN_TRUE, только если объект удовлетворяет запросу независимо от того, содержит ли индекс соответствующие ключи запроса. Подобным образом, функция должна возвращатьGIN_FALSE, только если объект не удовлетворяет запросу независимо от того, содержит ли он ключиGIN_MAYBE. Если результат зависит от элементовGIN_MAYBE, то есть соответствие нельзя утверждать или отрицать в зависимости от известных ключей запроса, функция должна вернутьGIN_MAYBE.Когда в векторе
checkнет элементовGIN_MAYBE, возвращаемое значениеGIN_MAYBEравнозначно установленному флагуrecheckв булевой функцииconsistent.
Кроме того, GIN нужно каким-то образом сортировать значения ключа, хранящиеся в индексе. Класс операторов может определить порядок сортировки, указав метод сравнения:
int compare(Datum a, Datum b)Сравнивает два ключа (не индексированные объекты!) и возвращает целое меньше нуля, ноль или целое больше нуля, показывающее, что первый ключ меньше, равен или больше второго. Ключи NULL никогда не передаются этой функции.
Если же класс операторов не определяет метод compare, GIN попытается найти класс операторов B-дерева по умолчанию для типа данных ключа индекса и воспользоваться его функцией сравнения. Если класс операторов GIN предназначен только для одного типа данных, рекомендуется задавать функцию сравнения в этом классе операторов, так как поиск класса операторов B-дерева занимает несколько циклов. Однако для полиморфных классов операторов GIN (например, array_ops) задать одну функцию сравнения обычно не представляется возможным.
Дополнительно класс операторов для GIN может предоставить следующие методы:
int comparePartial(Datum partial_key, Datum key, StrategyNumber n, Pointer extra_data)Сравнивает ключ запроса с частичным соответствием с ключом индекса. Возвращает целое число, знак которого отражает результат сравнения: отрицательное число означает, что ключ индекса не соответствует запросу, но нужно продолжать сканирование индекса; ноль означает, что ключ индекса соответствует запросу; положительное число означает, что сканирование индекса нужно прекратить, так как других соответствий не будет. Функции передаётся номер стратегии
nоператора, сформировавшего запрос частичного соответствия, на случай, если нужно знать его смысл, чтобы определить, когда прекращать сканирование. Кроме того, ей передаётсяextra_data— соответствующий элемент массива дополнительных данных, сформированного функциейextractQuery, либоNULL, если дополнительных данных нет. Значения NULL этой функции никогда не передаются.void options(local_relopts *relopts)Определяет набор видимых пользователю параметров, управляющих поведением класса операторов.
Функции
optionsпередаётся указатель на структуруlocal_relopts, в которую нужно внести набор параметров, относящихся к классу операторов. Обращаться к этим параметрам из других опорных функций можно с помощью макросовPG_HAS_OPCLASS_OPTIONS()иPG_GET_OPCLASS_OPTIONS().Так как в GIN и извлечение ключа из индексируемых значений, и его представление допускают гибкость, могут быть полезны параметры для настройки этого индекса.
Для поддержки проверок на «частичное соответствие» класс операторов должен предоставить метод comparePartial, а метод extractQuery должен устанавливать параметр pmatch, когда встречается запрос на частичное соответствие. За подробностями обратитесь к Подразделу 67.4.4.2.
Фактические типы данных различных значений Datum, упоминаемых выше, зависят от класса операторов. Значения объектов, передаваемые в extractValue, всегда имеют входной тип класса операторов, а все значения ключей должны быть типа, заданного параметром STORAGE для класса. Типом аргумента query, передаваемого функциям extractQuery, consistent и triConsistent, будет тот тип, что указан в качестве типа правого операнда оператора-члена класса, определяемого по номеру стратегии. Это не обязательно должен быть индексируемый тип, достаточно лишь, чтобы из него можно было извлечь значения ключей, имеющие нужный тип. Однако рекомендуется, чтобы в SQL-объявлениях этих трёх опорных функций для аргумента query назначался индексируемый тип класса операторов, даже несмотря на то, что фактический тип может быть другим, в зависимости от оператора.
67.4.4. Реализация #
Внутри индекс GIN содержит B-дерево, построенное по ключам, где каждый ключ является элементом одного или нескольких индексированных объектов (например, членом массива) и где каждый кортеж на страницах листьев содержит либо указатель на B-дерево указателей на данные («дерево идентификаторов»), либо простой список указателей на данные («список идентификаторов»), когда этот список достаточно мал, чтобы уместиться в одном кортеже индекса вместе со значением ключа. Эти компоненты GIN-индекса показаны на Рисунке 67.1.
Начиная с PostgreSQL версии 9.1, в индекс могут быть включены значения ключей, равные NULL. Кроме того, в индекс вставляются NULL для индексируемых объектов, равных NULL или не содержащих ключей, согласно функции extractValue. Это позволяет находить при поиске пустые объекты, когда они должны быть найдены.
Составные индексы GIN реализуются в виде одного B-дерева по составным значениям (номер столбца, значение ключа). Значения ключей для различных столбцов могут быть разных типов.
Рисунок 67.1. Внутреннее устройство GIN
67.4.4.1. Методика быстрого обновления GIN #
Природа инвертированного индекса такова, что обновление GIN обычно медленная операция: при добавлении или изменении одной строки данных может потребоваться выполнить множество добавлений записей в индекс (для каждого ключа, извлечённого из индексируемого объекта). GIN может отложить большой объём этой работы, вставляя новые кортежи во временный, несортированный список записей, ожидающих индексации. Когда таблица очищается, автоматически анализируется, вызывается функция gin_clean_pending_list или размер этого списка временного списка становится больше чем gin_pending_list_limit, записи переносятся в основную структуру данных GIN теми же методами массового добавления данных, что и при начальном создании индекса. Это значительно увеличивает скорость обновления индекса GIN, даже с учётом дополнительных издержек при очистке. К тому же эту дополнительную работу можно выполнить в фоновом процессе, а не в процессе, непосредственно выполняющем запросы.
Основной недостаток такого подхода состоит в том, что при поиске необходимо не только проверить обычный индекс, но и просканировать список ожидающих записей, так что если этот список большой, поиск значительно замедляется. Ещё один недостаток состоит в том, что хотя в основном изменения производятся быстро, изменение, при котором этот список оказывается «слишком большим», влечёт необходимость немедленной очистки и поэтому выполняется гораздо дольше остальных изменений. Минимизировать эти недостатки можно, правильно организовав автоочистку.
Если выдержанность времени операций важнее скорости обновления, применение списка ожидающих записей можно отключить, выключив параметр хранения fastupdate для индекса GIN. За подробностями обратитесь к CREATE INDEX.
67.4.4.2. Алгоритм частичного соответствия #
GIN может поддерживать проверки «частичного соответствия», когда запрос выявляет не точное соответствие одному или нескольким ключам, а возможные соответствия, попадающие в достаточно узкий диапазон значений ключей (при порядке сортировки ключей, определённым опорным методом compare). В этом случае метод extractQuery возвращает не значение ключа, которое должно соответствовать точно, а значение, определяющее нижнюю границу искомого диапазона, и устанавливает флаг pmatch. Затем диапазон ключей сканируется методом comparePartial. Метод comparePartial должен вернуть ноль при соответствии ключа индекса, отрицательное значение, если соответствия нет, но нужно продолжать проверку диапазона, и положительное значение, если ключ индекса оказался за искомым диапазоном.
67.4.5. Приёмы и советы по применению GIN #
- Создание или добавление
Добавление объектов в индекс GIN может выполняться медленно, так как для каждого объекта скорее всего потребуется добавлять множество ключей. Поэтому при массовом добавлении данных в таблицу рекомендуется удалить индекс GIN и пересоздать его по окончании добавления.
Когда для GIN включён режим
fastupdate(за подробностями обратитесь к Подразделу 67.4.4.1), издержки меньше, чем когда он отключён. Но при очень большом объёме изменений всё же лучше удалить и заново создать индекс.- maintenance_work_mem
Время построения индекса GIN очень сильно зависит от параметра
maintenance_work_mem; не стоит экономить на рабочей памяти при создании индекса.- gin_pending_list_limit
В процессе последовательных добавлений в существующий индекс GIN с включённым режимом
fastupdate, система будет очищать список ожидающих индексации записей, когда его размер будет превышатьgin_pending_list_limit. Во избежание значительных колебаний конечного времени ответа имеет смысл проводить очистку этого списка в фоновом режиме (то есть, применяя автоочистку). Избежать операций очистки на переднем плане можно, увеличивgin_pending_list_limitили проводя автоочистку более активно. Однако если вследствие увеличения порога операции очистки запустится очистка на переднем плане, она будет выполняться ещё дольше.Значение
gin_pending_list_limitможно переопределить для отдельных индексов GIN, изменив их параметры хранения, что позволяет задавать для каждого индекса GIN свой порог очистки. Например, можно увеличить порог только для часто обновляемых индексов GIN и оставить его низким для остальных.- gin_fuzzy_search_limit
Основной целью разработки индексов GIN было обеспечить поддержку хорошо расширяемого полнотекстового поиска в Postgres Pro, а при полнотекстовом поиске нередко возникают ситуации, когда возвращается очень большой набор результатов. Однако чаще всего так происходит, когда запрос содержит очень часто встречающиеся слова, так что полученный результат всё равно оказывается бесполезным. Так как чтение множества записей с диска и последующая сортировка их может занять много времени, это неприемлемо в производственных условиях. (Заметьте, что поиск по индексу при этом выполняется очень быстро.)
Для управляемого выполнения таких запросов в GIN введено настраиваемое мягкое ограничение сверху для числа возвращаемых строк: конфигурационный параметр
gin_fuzzy_search_limit. По умолчанию он равен 0 (то есть ограничение отсутствует). Если он имеет ненулевое значение, возвращаемый набор строк будет случайно выбранным подмножеством всего набора результатов.«Мягким» оно называется потому, что фактическое число возвращаемых строк может несколько отличаться от заданного значения, в зависимости от запроса и качества системного генератора случайных чисел.
Из практики, со значениями в несколько тысяч (например, 5000 — 20000) получаются приемлемые результаты.
67.4.6. Ограничения #
GIN полагает, что индексируемые операторы являются строгими. Это означает, что функция extractValue вовсе не будет вызываться для значений NULL (вместо этого будет автоматически создаваться пустая запись в индексе), так же как и extractQuery не будет вызываться с искомым значением NULL (при этом сразу предполагается, что запрос не удовлетворяется). Заметьте однако, что при этом поддерживаются ключи NULL, содержащиеся в составных объектах или искомых значениях.
67.4.7. Примеры #
В базовый дистрибутив Postgres Pro включены классы операторов GIN, перечисленные ранее в Таблице 67.3. Также классы операторов GIN содержатся в следующих модулях contrib:
btree_ginФункциональность B-дерева для различных типов данных
hstoreМодуль для хранения пар (ключ, значение)
intarrayРасширенная поддержка
int[]pg_trgmСхожесть текста на основе статистики триграмм
67.4. GIN Indexes #
67.4.1. Introduction #
GIN stands for Generalized Inverted Index. GIN is designed for handling cases where the items to be indexed are composite values, and the queries to be handled by the index need to search for element values that appear within the composite items. For example, the items could be documents, and the queries could be searches for documents containing specific words.
We use the word item to refer to a composite value that is to be indexed, and the word key to refer to an element value. GIN always stores and searches for keys, not item values per se.
A GIN index stores a set of (key, posting list) pairs, where a posting list is a set of row IDs in which the key occurs. The same row ID can appear in multiple posting lists, since an item can contain more than one key. Each key value is stored only once, so a GIN index is very compact for cases where the same key appears many times.
GIN is generalized in the sense that the GIN access method code does not need to know the specific operations that it accelerates. Instead, it uses custom strategies defined for particular data types. The strategy defines how keys are extracted from indexed items and query conditions, and how to determine whether a row that contains some of the key values in a query actually satisfies the query.
One advantage of GIN is that it allows the development of custom data types with the appropriate access methods, by an expert in the domain of the data type, rather than a database expert. This is much the same advantage as using GiST.
The GIN implementation in Postgres Pro is primarily maintained by Teodor Sigaev and Oleg Bartunov. There is more information about GIN on their website.
67.4.2. Built-in Operator Classes #
The core Postgres Pro distribution includes the GIN operator classes shown in Table 67.3. (Some of the optional modules described in Appendix F provide additional GIN operator classes.)
Table 67.3. Built-in GIN Operator Classes
| Name | Indexable Operators |
|---|---|
array_ops | && (anyarray,anyarray) |
@> (anyarray,anyarray) | |
<@ (anyarray,anyarray) | |
= (anyarray,anyarray) | |
jsonb_ops | @> (jsonb,jsonb) |
@? (jsonb,jsonpath) | |
@@ (jsonb,jsonpath) | |
? (jsonb,text) | |
?| (jsonb,text[]) | |
?& (jsonb,text[]) | |
jsonb_path_ops | @> (jsonb,jsonb) |
@? (jsonb,jsonpath) | |
@@ (jsonb,jsonpath) | |
tsvector_ops | @@ (tsvector,tsquery) |
Of the two operator classes for type jsonb, jsonb_ops is the default. jsonb_path_ops supports fewer operators but offers better performance for those operators. See Section 8.14.4 for details.
67.4.3. Extensibility #
The GIN interface has a high level of abstraction, requiring the access method implementer only to implement the semantics of the data type being accessed. The GIN layer itself takes care of concurrency, logging and searching the tree structure.
All it takes to get a GIN access method working is to implement a few user-defined methods, which define the behavior of keys in the tree and the relationships between keys, indexed items, and indexable queries. In short, GIN combines extensibility with generality, code reuse, and a clean interface.
There are two methods that an operator class for GIN must provide:
Datum *extractValue(Datum itemValue, int32 *nkeys, bool **nullFlags)Returns a palloc'd array of keys given an item to be indexed. The number of returned keys must be stored into
*nkeys. If any of the keys can be null, also palloc an array of*nkeysboolfields, store its address at*nullFlags, and set these null flags as needed.*nullFlagscan be leftNULL(its initial value) if all keys are non-null. The return value can beNULLif the item contains no keys.Datum *extractQuery(Datum query, int32 *nkeys, StrategyNumber n, bool **pmatch, Pointer **extra_data, bool **nullFlags, int32 *searchMode)Returns a palloc'd array of keys given a value to be queried; that is,
queryis the value on the right-hand side of an indexable operator whose left-hand side is the indexed column.nis the strategy number of the operator within the operator class (see Section 40.16.2). Often,extractQuerywill need to consultnto determine the data type ofqueryand the method it should use to extract key values. The number of returned keys must be stored into*nkeys. If any of the keys can be null, also palloc an array of*nkeysboolfields, store its address at*nullFlags, and set these null flags as needed.*nullFlagscan be leftNULL(its initial value) if all keys are non-null. The return value can beNULLif thequerycontains no keys.searchModeis an output argument that allowsextractQueryto specify details about how the search will be done. If*searchModeis set toGIN_SEARCH_MODE_DEFAULT(which is the value it is initialized to before call), only items that match at least one of the returned keys are considered candidate matches. If*searchModeis set toGIN_SEARCH_MODE_INCLUDE_EMPTY, then in addition to items containing at least one matching key, items that contain no keys at all are considered candidate matches. (This mode is useful for implementing is-subset-of operators, for example.) If*searchModeis set toGIN_SEARCH_MODE_ALL, then all non-null items in the index are considered candidate matches, whether they match any of the returned keys or not. (This mode is much slower than the other two choices, since it requires scanning essentially the entire index, but it may be necessary to implement corner cases correctly. An operator that needs this mode in most cases is probably not a good candidate for a GIN operator class.) The symbols to use for setting this mode are defined inaccess/gin.h.pmatchis an output argument for use when partial match is supported. To use it,extractQuerymust allocate an array of*nkeysbools and store its address at*pmatch. Each element of the array should be set to true if the corresponding key requires partial match, false if not. If*pmatchis set toNULLthen GIN assumes partial match is not required. The variable is initialized toNULLbefore call, so this argument can simply be ignored by operator classes that do not support partial match.extra_datais an output argument that allowsextractQueryto pass additional data to theconsistentandcomparePartialmethods. To use it,extractQuerymust allocate an array of*nkeyspointers and store its address at*extra_data, then store whatever it wants to into the individual pointers. The variable is initialized toNULLbefore call, so this argument can simply be ignored by operator classes that do not require extra data. If*extra_datais set, the whole array is passed to theconsistentmethod, and the appropriate element to thecomparePartialmethod.
An operator class must also provide a function to check if an indexed item matches the query. It comes in two flavors, a Boolean consistent function, and a ternary triConsistent function. triConsistent covers the functionality of both, so providing triConsistent alone is sufficient. However, if the Boolean variant is significantly cheaper to calculate, it can be advantageous to provide both. If only the Boolean variant is provided, some optimizations that depend on refuting index items before fetching all the keys are disabled.
bool consistent(bool check[], StrategyNumber n, Datum query, int32 nkeys, Pointer extra_data[], bool *recheck, Datum queryKeys[], bool nullFlags[])Returns true if an indexed item satisfies the query operator with strategy number
n(or might satisfy it, if the recheck indication is returned). This function does not have direct access to the indexed item's value, since GIN does not store items explicitly. Rather, what is available is knowledge about which key values extracted from the query appear in a given indexed item. Thecheckarray has lengthnkeys, which is the same as the number of keys previously returned byextractQueryfor thisquerydatum. Each element of thecheckarray is true if the indexed item contains the corresponding query key, i.e., if (check[i] == true) the i-th key of theextractQueryresult array is present in the indexed item. The originalquerydatum is passed in case theconsistentmethod needs to consult it, and so are thequeryKeys[]andnullFlags[]arrays previously returned byextractQuery.extra_datais the extra-data array returned byextractQuery, orNULLif none.When
extractQueryreturns a null key inqueryKeys[], the correspondingcheck[]element is true if the indexed item contains a null key; that is, the semantics ofcheck[]are likeIS NOT DISTINCT FROM. Theconsistentfunction can examine the correspondingnullFlags[]element if it needs to tell the difference between a regular value match and a null match.On success,
*recheckshould be set to true if the heap tuple needs to be rechecked against the query operator, or false if the index test is exact. That is, a false return value guarantees that the heap tuple does not match the query; a true return value with*recheckset to false guarantees that the heap tuple does match the query; and a true return value with*recheckset to true means that the heap tuple might match the query, so it needs to be fetched and rechecked by evaluating the query operator directly against the originally indexed item.GinTernaryValue triConsistent(GinTernaryValue check[], StrategyNumber n, Datum query, int32 nkeys, Pointer extra_data[], Datum queryKeys[], bool nullFlags[])triConsistentis similar toconsistent, but instead of Booleans in thecheckvector, there are three possible values for each key:GIN_TRUE,GIN_FALSEandGIN_MAYBE.GIN_FALSEandGIN_TRUEhave the same meaning as regular Boolean values, whileGIN_MAYBEmeans that the presence of that key is not known. WhenGIN_MAYBEvalues are present, the function should only returnGIN_TRUEif the item certainly matches whether or not the index item contains the corresponding query keys. Likewise, the function must returnGIN_FALSEonly if the item certainly does not match, whether or not it contains theGIN_MAYBEkeys. If the result depends on theGIN_MAYBEentries, i.e., the match cannot be confirmed or refuted based on the known query keys, the function must returnGIN_MAYBE.When there are no
GIN_MAYBEvalues in thecheckvector, aGIN_MAYBEreturn value is the equivalent of setting therecheckflag in the Booleanconsistentfunction.
In addition, GIN must have a way to sort the key values stored in the index. The operator class can define the sort ordering by specifying a comparison method:
int compare(Datum a, Datum b)Compares two keys (not indexed items!) and returns an integer less than zero, zero, or greater than zero, indicating whether the first key is less than, equal to, or greater than the second. Null keys are never passed to this function.
Alternatively, if the operator class does not provide a compare method, GIN will look up the default btree operator class for the index key data type, and use its comparison function. It is recommended to specify the comparison function in a GIN operator class that is meant for just one data type, as looking up the btree operator class costs a few cycles. However, polymorphic GIN operator classes (such as array_ops) typically cannot specify a single comparison function.
An operator class for GIN can optionally supply the following methods:
int comparePartial(Datum partial_key, Datum key, StrategyNumber n, Pointer extra_data)Compare a partial-match query key to an index key. Returns an integer whose sign indicates the result: less than zero means the index key does not match the query, but the index scan should continue; zero means that the index key does match the query; greater than zero indicates that the index scan should stop because no more matches are possible. The strategy number
nof the operator that generated the partial match query is provided, in case its semantics are needed to determine when to end the scan. Also,extra_datais the corresponding element of the extra-data array made byextractQuery, orNULLif none. Null keys are never passed to this function.void options(local_relopts *relopts)Defines a set of user-visible parameters that control operator class behavior.
The
optionsfunction is passed a pointer to alocal_reloptsstruct, which needs to be filled with a set of operator class specific options. The options can be accessed from other support functions using thePG_HAS_OPCLASS_OPTIONS()andPG_GET_OPCLASS_OPTIONS()macros.Since both key extraction of indexed values and representation of the key in GIN are flexible, they may depend on user-specified parameters.
To support “partial match” queries, an operator class must provide the comparePartial method, and its extractQuery method must set the pmatch parameter when a partial-match query is encountered. See Section 67.4.4.2 for details.
The actual data types of the various Datum values mentioned above vary depending on the operator class. The item values passed to extractValue are always of the operator class's input type, and all key values must be of the class's STORAGE type. The type of the query argument passed to extractQuery, consistent and triConsistent is whatever is the right-hand input type of the class member operator identified by the strategy number. This need not be the same as the indexed type, so long as key values of the correct type can be extracted from it. However, it is recommended that the SQL declarations of these three support functions use the opclass's indexed data type for the query argument, even though the actual type might be something else depending on the operator.
67.4.4. Implementation #
Internally, a GIN index contains a B-tree index constructed over keys, where each key is an element of one or more indexed items (a member of an array, for example) and where each tuple in a leaf page contains either a pointer to a B-tree of heap pointers (a “posting tree”), or a simple list of heap pointers (a “posting list”) when the list is small enough to fit into a single index tuple along with the key value. Figure 67.1 illustrates these components of a GIN index.
As of PostgreSQL 9.1, null key values can be included in the index. Also, placeholder nulls are included in the index for indexed items that are null or contain no keys according to extractValue. This allows searches that should find empty items to do so.
Multicolumn GIN indexes are implemented by building a single B-tree over composite values (column number, key value). The key values for different columns can be of different types.
Figure 67.1. GIN Internals
67.4.4.1. GIN Fast Update Technique #
Updating a GIN index tends to be slow because of the intrinsic nature of inverted indexes: inserting or updating one heap row can cause many inserts into the index (one for each key extracted from the indexed item). GIN is capable of postponing much of this work by inserting new tuples into a temporary, unsorted list of pending entries. When the table is vacuumed or autoanalyzed, or when gin_clean_pending_list function is called, or if the pending list becomes larger than gin_pending_list_limit, the entries are moved to the main GIN data structure using the same bulk insert techniques used during initial index creation. This greatly improves GIN index update speed, even counting the additional vacuum overhead. Moreover the overhead work can be done by a background process instead of in foreground query processing.
The main disadvantage of this approach is that searches must scan the list of pending entries in addition to searching the regular index, and so a large list of pending entries will slow searches significantly. Another disadvantage is that, while most updates are fast, an update that causes the pending list to become “too large” will incur an immediate cleanup cycle and thus be much slower than other updates. Proper use of autovacuum can minimize both of these problems.
If consistent response time is more important than update speed, use of pending entries can be disabled by turning off the fastupdate storage parameter for a GIN index. See CREATE INDEX for details.
67.4.4.2. Partial Match Algorithm #
GIN can support “partial match” queries, in which the query does not determine an exact match for one or more keys, but the possible matches fall within a reasonably narrow range of key values (within the key sorting order determined by the compare support method). The extractQuery method, instead of returning a key value to be matched exactly, returns a key value that is the lower bound of the range to be searched, and sets the pmatch flag true. The key range is then scanned using the comparePartial method. comparePartial must return zero for a matching index key, less than zero for a non-match that is still within the range to be searched, or greater than zero if the index key is past the range that could match.
67.4.5. GIN Tips and Tricks #
- Create vs. insert
Insertion into a GIN index can be slow due to the likelihood of many keys being inserted for each item. So, for bulk insertions into a table it is advisable to drop the GIN index and recreate it after finishing bulk insertion.
When
fastupdateis enabled for GIN (see Section 67.4.4.1 for details), the penalty is less than when it is not. But for very large updates it may still be best to drop and recreate the index.- maintenance_work_mem
Build time for a GIN index is very sensitive to the
maintenance_work_memsetting; it doesn't pay to skimp on work memory during index creation.- gin_pending_list_limit
During a series of insertions into an existing GIN index that has
fastupdateenabled, the system will clean up the pending-entry list whenever the list grows larger thangin_pending_list_limit. To avoid fluctuations in observed response time, it's desirable to have pending-list cleanup occur in the background (i.e., via autovacuum). Foreground cleanup operations can be avoided by increasinggin_pending_list_limitor making autovacuum more aggressive. However, enlarging the threshold of the cleanup operation means that if a foreground cleanup does occur, it will take even longer.gin_pending_list_limitcan be overridden for individual GIN indexes by changing storage parameters, which allows each GIN index to have its own cleanup threshold. For example, it's possible to increase the threshold only for the GIN index which can be updated heavily, and decrease it otherwise.- gin_fuzzy_search_limit
The primary goal of developing GIN indexes was to create support for highly scalable full-text search in Postgres Pro, and there are often situations when a full-text search returns a very large set of results. Moreover, this often happens when the query contains very frequent words, so that the large result set is not even useful. Since reading many tuples from the disk and sorting them could take a lot of time, this is unacceptable for production. (Note that the index search itself is very fast.)
To facilitate controlled execution of such queries, GIN has a configurable soft upper limit on the number of rows returned: the
gin_fuzzy_search_limitconfiguration parameter. It is set to 0 (meaning no limit) by default. If a non-zero limit is set, then the returned set is a subset of the whole result set, chosen at random.“Soft” means that the actual number of returned results could differ somewhat from the specified limit, depending on the query and the quality of the system's random number generator.
From experience, values in the thousands (e.g., 5000 — 20000) work well.
67.4.6. Limitations #
GIN assumes that indexable operators are strict. This means that extractValue will not be called at all on a null item value (instead, a placeholder index entry is created automatically), and extractQuery will not be called on a null query value either (instead, the query is presumed to be unsatisfiable). Note however that null key values contained within a non-null composite item or query value are supported.
67.4.7. Examples #
The core Postgres Pro distribution includes the GIN operator classes previously shown in Table 67.3. The following contrib modules also contain GIN operator classes:
btree_ginB-tree equivalent functionality for several data types
hstoreModule for storing (key, value) pairs
intarrayEnhanced support for
int[]pg_trgmText similarity using trigram matching