59.3. Extensibility
Traditionally, implementing a new index access method meant a lot of difficult work. It was necessary to understand the inner workings of the database, such as the lock manager and Write-Ahead Log. TheGiST interface has a high level of abstraction, requiring the access method implementer only to implement the semantics of the data type being accessed. TheGiST layer itself takes care of concurrency, logging and searching the tree structure.
So if you index, say, an image collection with aPostgres Pro B-tree, you can only issue queries such as“is imagex equal to imagey”,“is imagex less than imagey” and“is imagex greater than imagey”. Depending on how you define“equals”,“less than” and“greater than” in this context, this could be useful. However, by using aGiST based index, you could create ways to ask domain-specific questions, perhaps“find all images of horses” or“find all over-exposed images”.
All it takes to get aGiST access method up and running is to implement several user-defined methods, which define the behavior of keys in the tree. Of course these methods have to be pretty fancy to support fancy queries, but for all the standard queries (B-trees, R-trees, etc.) they're relatively straightforward. In short,GiST combines extensibility along with generality, code reuse, and a clean interface.
There are seven methods that an index operator class forGiST must provide, and two that are optional. Correctness of the index is ensured by proper implementation of thesame
,consistent
andunion
methods, while efficiency (size and speed) of the index will depend on thepenalty
andpicksplit
methods. The remaining two basic methods arecompress
anddecompress
, which allow an index to have internal tree data of a different type than the data it indexes. The leaves are to be of the indexed data type, while the other tree nodes can be of any C struct (but you still have to followPostgres Pro data type rules here, see aboutvarlena
for variable sized data). If the tree's internal data type exists at the SQL level, theSTORAGE
option of theCREATE OPERATOR CLASS
command can be used. The optional eighth method isdistance
, which is needed if the operator class wishes to support ordered scans (nearest-neighbor searches). The optional ninth methodfetch
is needed if the operator class wishes to support index-only scans.
consistent
Given an index entry
p
and a query valueq
, this function determines whether the index entry is“consistent” with the query; that is, could the predicate“indexed_column
indexable_operator
q
” be true for any row represented by the index entry? For a leaf index entry this is equivalent to testing the indexable condition, while for an internal tree node this determines whether it is necessary to scan the subtree of the index represented by the tree node. When the result istrue
, arecheck
flag must also be returned. This indicates whether the predicate is certainly true or only possibly true. Ifrecheck
=false
then the index has tested the predicate condition exactly, whereas ifrecheck
=true
the row is only a candidate match. In that case the system will automatically evaluate theindexable_operator
against the actual row value to see if it is really a match. This convention allowsGiST to support both lossless and lossy index structures.TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_consistent(internal, data_type, smallint, oid, internal)RETURNS boolAS 'MODULE_PATHNAME'LANGUAGE C STRICT;
And the matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_consistent);Datummy_consistent(PG_FUNCTION_ARGS){ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0); data_type *query = PG_GETARG_DATA_TYPE_P(1); StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2); /* Oid subtype = PG_GETARG_OID(3); */ bool *recheck = (bool *) PG_GETARG_POINTER(4); data_type *key = DatumGetDataType(entry->key); bool retval; /* * determine return value as a function of strategy, key and query. * * Use GIST_LEAF(entry) to know where you're called in the index tree, * which comes handy when supporting the = operator for example (you could * check for non empty union() in non-leaf nodes and equality in leaf * nodes). */ *recheck = true; /* or false if check is exact */ PG_RETURN_BOOL(retval);}
union
TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_union(internal, internal)RETURNS internalAS 'MODULE_PATHNAME'LANGUAGE C STRICT;
And the matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_union);Datummy_union(PG_FUNCTION_ARGS){ GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0); GISTENTRY *ent = entryvec->vector; data_type *out, *tmp, *old; int numranges, i = 0; numranges = entryvec->n; tmp = DatumGetDataType(ent[0].key); out = tmp; if (numranges == 1) { out = data_type_deep_copy(tmp); PG_RETURN_DATA_TYPE_P(out); } for (i = 1; i < numranges; i++) { old = out; tmp = DatumGetDataType(ent[i].key); out = my_union_implementation(out, tmp); } PG_RETURN_DATA_TYPE_P(out);}
As you can see, in this skeleton we're dealing with a data type where
union(X, Y, Z) = union(union(X, Y), Z)
. It's easy enough to support data types where this is not the case, by implementing the proper union algorithm in thisGiST support method.compress
Converts the data item into a format suitable for physical storage in an index page.
TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_compress(internal)RETURNS internalAS 'MODULE_PATHNAME'LANGUAGE C STRICT;
And the matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_compress);Datummy_compress(PG_FUNCTION_ARGS){ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0); GISTENTRY *retval; if (entry->leafkey) { /* replace entry->key with a compressed version */ compressed_data_type *compressed_data = palloc(sizeof(compressed_data_type)); /* fill *compressed_data from entry->key ... */ retval = palloc(sizeof(GISTENTRY)); gistentryinit(*retval, PointerGetDatum(compressed_data), entry->rel, entry->page, entry->offset, FALSE); } else { /* typically we needn't do anything with non-leaf entries */ retval = entry; } PG_RETURN_POINTER(retval);}
decompress
TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_decompress(internal)RETURNS internalAS 'MODULE_PATHNAME'LANGUAGE C STRICT;
And the matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_decompress);Datummy_decompress(PG_FUNCTION_ARGS){ PG_RETURN_POINTER(PG_GETARG_POINTER(0));}
The above skeleton is suitable for the case where no decompression is needed.
penalty
TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_penalty(internal, internal, internal)RETURNS internalAS 'MODULE_PATHNAME'LANGUAGE C STRICT; -- in some cases penalty functions need not be strict
And the matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_penalty);Datummy_penalty(PG_FUNCTION_ARGS){ GISTENTRY *origentry = (GISTENTRY *) PG_GETARG_POINTER(0); GISTENTRY *newentry = (GISTENTRY *) PG_GETARG_POINTER(1); float *penalty = (float *) PG_GETARG_POINTER(2); data_type *orig = DatumGetDataType(origentry->key); data_type *new = DatumGetDataType(newentry->key); *penalty = my_penalty_implementation(orig, new); PG_RETURN_POINTER(penalty);}
picksplit
TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_picksplit(internal, internal)RETURNS internalAS 'MODULE_PATHNAME'LANGUAGE C STRICT;
And the matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_picksplit);Datummy_picksplit(PG_FUNCTION_ARGS){ GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0); OffsetNumber maxoff = entryvec->n - 1; GISTENTRY *ent = entryvec->vector; GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1); int i, nbytes; OffsetNumber *left, *right; data_type *tmp_union; data_type *unionL; data_type *unionR; GISTENTRY **raw_entryvec; maxoff = entryvec->n - 1; nbytes = (maxoff + 1) * sizeof(OffsetNumber); v->spl_left = (OffsetNumber *) palloc(nbytes); left = v->spl_left; v->spl_nleft = 0; v->spl_right = (OffsetNumber *) palloc(nbytes); right = v->spl_right; v->spl_nright = 0; unionL = NULL; unionR = NULL; /* Initialize the raw entry vector. */ raw_entryvec = (GISTENTRY **) malloc(entryvec->n * sizeof(void *)); for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i)) raw_entryvec[i] = &(entryvec->vector[i]); for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i)) { int real_index = raw_entryvec[i] - entryvec->vector; tmp_union = DatumGetDataType(entryvec->vector[real_index].key); Assert(tmp_union != NULL); /* * Choose where to put the index entries and update unionL and unionR * accordingly. Append the entries to either v->spl_left or * v->spl_right, and care about the counters. */ if (my_choice_is_left(unionL, curl, unionR, curr)) { if (unionL == NULL) unionL = tmp_union; else unionL = my_union_implementation(unionL, tmp_union); *left = real_index; ++left; ++(v->spl_nleft); } else { /* * Same on the right */ } } v->spl_ldatum = DataTypeGetDatum(unionL); v->spl_rdatum = DataTypeGetDatum(unionR); PG_RETURN_POINTER(v);}
Like
penalty
, thepicksplit
function is crucial to good performance of the index. Designing suitablepenalty
andpicksplit
implementations is where the challenge of implementing well-performingGiST indexes lies.same
Returns true if two index entries are identical, false otherwise.
TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_same(internal, internal, internal)RETURNS internalAS 'MODULE_PATHNAME'LANGUAGE C STRICT;
And the matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_same);Datummy_same(PG_FUNCTION_ARGS){ prefix_range *v1 = PG_GETARG_PREFIX_RANGE_P(0); prefix_range *v2 = PG_GETARG_PREFIX_RANGE_P(1); bool *result = (bool *) PG_GETARG_POINTER(2); *result = my_eq(v1, v2); PG_RETURN_POINTER(result);}
distance
TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_distance(internal, data_type, smallint, oid)RETURNS float8AS 'MODULE_PATHNAME'LANGUAGE C STRICT;
And the matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_distance);Datummy_distance(PG_FUNCTION_ARGS){ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0); data_type *query = PG_GETARG_DATA_TYPE_P(1); StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2); /* Oid subtype = PG_GETARG_OID(3); */ /* bool *recheck = (bool *) PG_GETARG_POINTER(4); */ data_type *key = DatumGetDataType(entry->key); double retval; /* * determine return value as a function of strategy, key and query. */ PG_RETURN_FLOAT8(retval);}
The arguments to the
distance
function are identical to the arguments of theconsistent
function.fetch
TheSQL declaration of the function must look like this:
CREATE OR REPLACE FUNCTION my_fetch(internal)RETURNS internalAS 'MODULE_PATHNAME'LANGUAGE C STRICT;
The matching code in the C module could then follow this skeleton:
PG_FUNCTION_INFO_V1(my_fetch);Datummy_fetch(PG_FUNCTION_ARGS){ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0); input_data_type *in = DatumGetPointer(entry->key); fetched_data_type *fetched_data; GISTENTRY *retval; retval = palloc(sizeof(GISTENTRY)); fetched_data = palloc(sizeof(fetched_data_type)); /* * Convert 'fetched_data' into the a Datum of the original datatype. */ /* fill *retval from fetched_data. */ gistentryinit(*retval, PointerGetDatum(converted_datum), entry->rel, entry->page, entry->offset, FALSE); PG_RETURN_POINTER(retval);}