64.4. GIN Indexes#
64.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 worditem to refer to a composite value that is to be indexed, and the wordkey to refer to an element value.GIN always stores and searches for keys, not item values per se. AGIN index stores a set of (key, posting list) pairs, where aposting 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 aGIN index is very compact for cases where the same key appears many times. GIN is generalized in the sense that theGIN 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 ofGIN 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 usingGiST. TheGIN implementation inPostgreSQL is primarily maintained by Teodor Sigaev and Oleg Bartunov. There is more information aboutGIN on theirwebsite.
64.4.2. Built-in Operator Classes#
The corePostgreSQL distribution includes theGIN operator classes shown inTable 64.3. (Some of the optional modules described inAppendix F provide additionalGIN operator classes.) Table 64.3. Built-inGIN Operator Classes Of the two operator classes for typeName 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)
jsonb
,jsonb_ops
is the default.jsonb_path_ops
supports fewer operators but offers better performance for those operators. SeeSection 8.14.4 for details.
64.4.3. Extensibility#
TheGIN interface has a high level of abstraction, requiring the access method implementer only to implement the semantics of the data type being accessed. TheGIN layer itself takes care of concurrency, logging and searching the tree structure. All it takes to get aGIN 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 forGIN must provide: Returns a palloc'd array of keys given an item to be indexed. The number of returned keys must be stored into Returns a palloc'd array of keys given a value to be queried; that is, An operator class must also provide a function to check if an indexed item matches the query. It comes in two flavors, a Boolean 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: 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 An operator class forGIN can optionally supply the following methods: 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 Defines a set of user-visible parameters that control operator class behavior. The Since both key extraction of indexed values and representation of the key inGIN are flexible, they may depend on user-specified parameters. To support“partial match” queries, an operator class must provide the The actual data types of the variousDatum *extractValue(Datum itemValue, int32 *nkeys, bool **nullFlags)
*nkeys
. If any of the keys can be null, also palloc an array of*nkeys
bool
fields, store its address at*nullFlags
, and set these null flags as needed.*nullFlags
can be leftNULL
(its initial value) if all keys are non-null. The return value can beNULL
if the item contains no keys.Datum *extractQuery(Datum query, int32 *nkeys, StrategyNumber n, bool **pmatch, Pointer **extra_data, bool **nullFlags, int32 *searchMode)
query
is the value on the right-hand side of an indexable operator whose left-hand side is the indexed column.n
is the strategy number of the operator within the operator class (seeSection 36.16.2). Often,extractQuery
will need to consultn
to determine the data type ofquery
and 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*nkeys
bool
fields, store its address at*nullFlags
, and set these null flags as needed.*nullFlags
can be leftNULL
(its initial value) if all keys are non-null. The return value can beNULL
if thequery
contains no keys.searchMode
is an output argument that allowsextractQuery
to specify details about how the search will be done. If*searchMode
is 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*searchMode
is 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*searchMode
is 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
.pmatch
is an output argument for use when partial match is supported. To use it,extractQuery
must allocate an array of*nkeys
bool
s 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*pmatch
is set toNULL
then GIN assumes partial match is not required. The variable is initialized toNULL
before call, so this argument can simply be ignored by operator classes that do not support partial match.extra_data
is an output argument that allowsextractQuery
to pass additional data to theconsistent
andcomparePartial
methods. To use it,extractQuery
must allocate an array of*nkeys
pointers and store its address at*extra_data
, then store whatever it wants to into the individual pointers. The variable is initialized toNULL
before call, so this argument can simply be ignored by operator classes that do not require extra data. If*extra_data
is set, the whole array is passed to theconsistent
method, and the appropriate element to thecomparePartial
method.consistent
function, and a ternarytriConsistent
function.triConsistent
covers the functionality of both, so providingtriConsistent
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[])
int compare(Datum a, Datum b)
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 asarray_ops
) typically cannot specify a single comparison function.int comparePartial(Datum partial_key, Datum key, StrategyNumber n, Pointer extra_data)
n
of 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_data
is the corresponding element of the extra-data array made byextractQuery
, orNULL
if none. Null keys are never passed to this function.void options(local_relopts *relopts)
options
function is passed a pointer to alocal_relopts
struct, 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.comparePartial
method, and itsextractQuery
method must set thepmatch
parameter when a partial-match query is encountered. SeeSection 64.4.4.2 for details.Datum
values mentioned above vary depending on the operator class. The item values passed toextractValue
are always of the operator class's input type, and all key values must be of the class'sSTORAGE
type. The type of thequery
argument passed toextractQuery
,consistent
andtriConsistent
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 thequery
argument, even though the actual type might be something else depending on the operator.
64.4.4. Implementation#
Internally, aGIN 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 64.1 illustrates these components of a GIN index.
As ofPostgreSQL 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 toextractValue
. This allows searches that should find empty items to do so.
MulticolumnGIN 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 64.1. GIN Internals Updating aGIN 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 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 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 the64.4.4.1. GIN Fast Update Technique#
gin_clean_pending_list
function is called, or if the pending list becomes larger thangin_pending_list_limit, the entries are moved to the mainGIN data structure using the same bulk insert techniques used during initial index creation. This greatly improvesGIN 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.fastupdate
storage parameter for aGIN index. SeeCREATE INDEX for details.64.4.4.2. Partial Match Algorithm#
compare
support method). TheextractQuery
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 thepmatch
flag true. The key range is then scanned using thecomparePartial
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.
64.4.5. GIN Tips and Tricks#
- Create vs. insert
Insertion into aGIN 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
fastupdate
is enabled forGIN (seeSection 64.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 aGIN index is very sensitive to the
maintenance_work_mem
setting; it doesn't pay to skimp on work memory during index creation.- gin_pending_list_limit
During a series of insertions into an existingGIN index that has
fastupdate
enabled, 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_limit
or 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_limit
can 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
64.4.6. Limitations#
64.4.7. Examples#
The corePostgreSQL distribution includes theGIN operator classes previously shown inTable 64.3. The following B-tree equivalent functionality for several data types Module for storing (key, value) pairs Enhanced support for Text similarity using trigram matchingcontrib
modules also containGIN operator classes:btree_gin
hstore
intarray
int[]
pg_trgm