1<!-- doc/src/sgml/gist.sgml -->
2
3<chapter id="gist">
4<title>GiST Indexes</title>
5
6   <indexterm>
7    <primary>index</primary>
8    <secondary>GiST</secondary>
9   </indexterm>
10
11<sect1 id="gist-intro">
12 <title>Introduction</title>
13
14 <para>
15   <acronym>GiST</acronym> stands for Generalized Search Tree.  It is a
16   balanced, tree-structured access method, that acts as a base template in
17   which to implement arbitrary indexing schemes. B-trees, R-trees and many
18   other indexing schemes can be implemented in <acronym>GiST</acronym>.
19 </para>
20
21 <para>
22  One advantage of <acronym>GiST</acronym> is that it allows the development
23  of custom data types with the appropriate access methods, by
24  an expert in the domain of the data type, rather than a database expert.
25 </para>
26
27  <para>
28    Some of the information here is derived from the University of California
29    at Berkeley's GiST Indexing Project
30    <ulink url="http://gist.cs.berkeley.edu/">web site</ulink> and
31    Marcel Kornacker's thesis,
32    <ulink url="http://www.sai.msu.su/~megera/postgres/gist/papers/concurrency/access-methods-for-next-generation.pdf.gz">
33    Access Methods for Next-Generation Database Systems</ulink>.
34    The <acronym>GiST</acronym>
35    implementation in <productname>PostgreSQL</productname> is primarily
36    maintained by Teodor Sigaev and Oleg Bartunov, and there is more
37    information on their
38    <ulink url="http://www.sai.msu.su/~megera/postgres/gist/">web site</ulink>.
39  </para>
40
41</sect1>
42
43<sect1 id="gist-builtin-opclasses">
44 <title>Built-in Operator Classes</title>
45
46 <para>
47  The core <productname>PostgreSQL</productname> distribution
48  includes the <acronym>GiST</acronym> operator classes shown in
49  <xref linkend="gist-builtin-opclasses-table"/>.
50  (Some of the optional modules described in <xref linkend="contrib"/>
51  provide additional <acronym>GiST</acronym> operator classes.)
52 </para>
53
54  <table id="gist-builtin-opclasses-table">
55   <title>Built-in <acronym>GiST</acronym> Operator Classes</title>
56   <tgroup cols="4">
57    <thead>
58     <row>
59      <entry>Name</entry>
60      <entry>Indexed Data Type</entry>
61      <entry>Indexable Operators</entry>
62      <entry>Ordering Operators</entry>
63     </row>
64    </thead>
65    <tbody>
66     <row>
67      <entry><literal>box_ops</literal></entry>
68      <entry><type>box</type></entry>
69      <entry>
70       <literal>&amp;&amp;</literal>
71       <literal>&amp;&gt;</literal>
72       <literal>&amp;&lt;</literal>
73       <literal>&amp;&lt;|</literal>
74       <literal>&gt;&gt;</literal>
75       <literal>&lt;&lt;</literal>
76       <literal>&lt;&lt;|</literal>
77       <literal>&lt;@</literal>
78       <literal>@&gt;</literal>
79       <literal>@</literal>
80       <literal>|&amp;&gt;</literal>
81       <literal>|&gt;&gt;</literal>
82       <literal>~</literal>
83       <literal>~=</literal>
84      </entry>
85      <entry>
86      </entry>
87     </row>
88     <row>
89      <entry><literal>circle_ops</literal></entry>
90      <entry><type>circle</type></entry>
91      <entry>
92       <literal>&amp;&amp;</literal>
93       <literal>&amp;&gt;</literal>
94       <literal>&amp;&lt;</literal>
95       <literal>&amp;&lt;|</literal>
96       <literal>&gt;&gt;</literal>
97       <literal>&lt;&lt;</literal>
98       <literal>&lt;&lt;|</literal>
99       <literal>&lt;@</literal>
100       <literal>@&gt;</literal>
101       <literal>@</literal>
102       <literal>|&amp;&gt;</literal>
103       <literal>|&gt;&gt;</literal>
104       <literal>~</literal>
105       <literal>~=</literal>
106      </entry>
107      <entry>
108       <literal>&lt;-&gt;</literal>
109      </entry>
110     </row>
111     <row>
112      <entry><literal>inet_ops</literal></entry>
113      <entry><type>inet</type>, <type>cidr</type></entry>
114      <entry>
115       <literal>&amp;&amp;</literal>
116       <literal>&gt;&gt;</literal>
117       <literal>&gt;&gt;=</literal>
118       <literal>&gt;</literal>
119       <literal>&gt;=</literal>
120       <literal>&lt;&gt;</literal>
121       <literal>&lt;&lt;</literal>
122       <literal>&lt;&lt;=</literal>
123       <literal>&lt;</literal>
124       <literal>&lt;=</literal>
125       <literal>=</literal>
126      </entry>
127      <entry>
128      </entry>
129     </row>
130     <row>
131      <entry><literal>point_ops</literal></entry>
132      <entry><type>point</type></entry>
133      <entry>
134       <literal>&gt;&gt;</literal>
135       <literal>&gt;^</literal>
136       <literal>&lt;&lt;</literal>
137       <literal>&lt;@</literal>
138       <literal>&lt;@</literal>
139       <literal>&lt;@</literal>
140       <literal>&lt;^</literal>
141       <literal>~=</literal>
142      </entry>
143      <entry>
144       <literal>&lt;-&gt;</literal>
145      </entry>
146     </row>
147     <row>
148      <entry><literal>poly_ops</literal></entry>
149      <entry><type>polygon</type></entry>
150      <entry>
151       <literal>&amp;&amp;</literal>
152       <literal>&amp;&gt;</literal>
153       <literal>&amp;&lt;</literal>
154       <literal>&amp;&lt;|</literal>
155       <literal>&gt;&gt;</literal>
156       <literal>&lt;&lt;</literal>
157       <literal>&lt;&lt;|</literal>
158       <literal>&lt;@</literal>
159       <literal>@&gt;</literal>
160       <literal>@</literal>
161       <literal>|&amp;&gt;</literal>
162       <literal>|&gt;&gt;</literal>
163       <literal>~</literal>
164       <literal>~=</literal>
165      </entry>
166      <entry>
167       <literal>&lt;-&gt;</literal>
168      </entry>
169     </row>
170     <row>
171      <entry><literal>range_ops</literal></entry>
172      <entry>any range type</entry>
173      <entry>
174       <literal>&amp;&amp;</literal>
175       <literal>&amp;&gt;</literal>
176       <literal>&amp;&lt;</literal>
177       <literal>&gt;&gt;</literal>
178       <literal>&lt;&lt;</literal>
179       <literal>&lt;@</literal>
180       <literal>-|-</literal>
181       <literal>=</literal>
182       <literal>@&gt;</literal>
183       <literal>@&gt;</literal>
184      </entry>
185      <entry>
186      </entry>
187     </row>
188     <row>
189      <entry><literal>tsquery_ops</literal></entry>
190      <entry><type>tsquery</type></entry>
191      <entry>
192       <literal>&lt;@</literal>
193       <literal>@&gt;</literal>
194      </entry>
195      <entry>
196      </entry>
197     </row>
198     <row>
199      <entry><literal>tsvector_ops</literal></entry>
200      <entry><type>tsvector</type></entry>
201      <entry>
202       <literal>@@</literal>
203      </entry>
204      <entry>
205      </entry>
206     </row>
207    </tbody>
208   </tgroup>
209  </table>
210
211 <para>
212  For historical reasons, the <literal>inet_ops</literal> operator class is
213  not the default class for types <type>inet</type> and <type>cidr</type>.
214  To use it, mention the class name in <command>CREATE INDEX</command>,
215  for example
216<programlisting>
217CREATE INDEX ON my_table USING GIST (my_inet_column inet_ops);
218</programlisting>
219 </para>
220
221</sect1>
222
223<sect1 id="gist-extensibility">
224 <title>Extensibility</title>
225
226 <para>
227   Traditionally, implementing a new index access method meant a lot of
228   difficult work.  It was necessary to understand the inner workings of the
229   database, such as the lock manager and Write-Ahead Log.  The
230   <acronym>GiST</acronym> interface has a high level of abstraction,
231   requiring the access method implementer only to implement the semantics of
232   the data type being accessed.  The <acronym>GiST</acronym> layer itself
233   takes care of concurrency, logging and searching the tree structure.
234 </para>
235
236 <para>
237   This extensibility should not be confused with the extensibility of the
238   other standard search trees in terms of the data they can handle.  For
239   example, <productname>PostgreSQL</productname> supports extensible B-trees
240   and hash indexes. That means that you can use
241   <productname>PostgreSQL</productname> to build a B-tree or hash over any
242   data type you want. But B-trees only support range predicates
243   (<literal>&lt;</literal>, <literal>=</literal>, <literal>&gt;</literal>),
244   and hash indexes only support equality queries.
245 </para>
246
247 <para>
248   So if you index, say, an image collection with a
249   <productname>PostgreSQL</productname> B-tree, you can only issue queries
250   such as <quote>is imagex equal to imagey</quote>, <quote>is imagex less
251   than imagey</quote> and <quote>is imagex greater than imagey</quote>.
252   Depending on how you define <quote>equals</quote>, <quote>less than</quote>
253   and <quote>greater than</quote> in this context, this could be useful.
254   However, by using a <acronym>GiST</acronym> based index, you could create
255   ways to ask domain-specific questions, perhaps <quote>find all images of
256   horses</quote> or <quote>find all over-exposed images</quote>.
257 </para>
258
259 <para>
260   All it takes to get a <acronym>GiST</acronym> access method up and running
261   is to implement several user-defined methods, which define the behavior of
262   keys in the tree. Of course these methods have to be pretty fancy to
263   support fancy queries, but for all the standard queries (B-trees,
264   R-trees, etc.) they're relatively straightforward. In short,
265   <acronym>GiST</acronym> combines extensibility along with generality, code
266   reuse, and a clean interface.
267  </para>
268
269 <para>
270   There are five methods that an index operator class for
271   <acronym>GiST</acronym> must provide, and four that are optional.
272   Correctness of the index is ensured
273   by proper implementation of the <function>same</function>, <function>consistent</function>
274   and <function>union</function> methods, while efficiency (size and speed) of the
275   index will depend on the <function>penalty</function> and <function>picksplit</function>
276   methods.
277   Two optional methods are <function>compress</function> and
278   <function>decompress</function>, which allow an index to have internal tree data of
279   a different type than the data it indexes. The leaves are to be of the
280   indexed data type, while the other tree nodes can be of any C struct (but
281   you still have to follow <productname>PostgreSQL</productname> data type rules here,
282   see about <literal>varlena</literal> for variable sized data). If the tree's
283   internal data type exists at the SQL level, the <literal>STORAGE</literal> option
284   of the <command>CREATE OPERATOR CLASS</command> command can be used.
285   The optional eighth method is <function>distance</function>, which is needed
286   if the operator class wishes to support ordered scans (nearest-neighbor
287   searches). The optional ninth method <function>fetch</function> is needed if the
288   operator class wishes to support index-only scans, except when the
289   <function>compress</function> method is omitted.
290 </para>
291
292 <variablelist>
293    <varlistentry>
294     <term><function>consistent</function></term>
295     <listitem>
296      <para>
297       Given an index entry <literal>p</literal> and a query value <literal>q</literal>,
298       this function determines whether the index entry is
299       <quote>consistent</quote> with the query; that is, could the predicate
300       <quote><replaceable>indexed_column</replaceable>
301       <replaceable>indexable_operator</replaceable> <literal>q</literal></quote> be true for
302       any row represented by the index entry?  For a leaf index entry this is
303       equivalent to testing the indexable condition, while for an internal
304       tree node this determines whether it is necessary to scan the subtree
305       of the index represented by the tree node.  When the result is
306       <literal>true</literal>, a <literal>recheck</literal> flag must also be returned.
307       This indicates whether the predicate is certainly true or only possibly
308       true.  If <literal>recheck</literal> = <literal>false</literal> then the index has
309       tested the predicate condition exactly, whereas if <literal>recheck</literal>
310       = <literal>true</literal> the row is only a candidate match.  In that case the
311       system will automatically evaluate the
312       <replaceable>indexable_operator</replaceable> against the actual row value to see
313       if it is really a match.  This convention allows
314       <acronym>GiST</acronym> to support both lossless and lossy index
315       structures.
316      </para>
317
318      <para>
319        The <acronym>SQL</acronym> declaration of the function must look like this:
320
321<programlisting>
322CREATE OR REPLACE FUNCTION my_consistent(internal, data_type, smallint, oid, internal)
323RETURNS bool
324AS 'MODULE_PATHNAME'
325LANGUAGE C STRICT;
326</programlisting>
327
328        And the matching code in the C module could then follow this skeleton:
329
330<programlisting>
331PG_FUNCTION_INFO_V1(my_consistent);
332
333Datum
334my_consistent(PG_FUNCTION_ARGS)
335{
336    GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
337    data_type  *query = PG_GETARG_DATA_TYPE_P(1);
338    StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
339    /* Oid subtype = PG_GETARG_OID(3); */
340    bool       *recheck = (bool *) PG_GETARG_POINTER(4);
341    data_type  *key = DatumGetDataType(entry-&gt;key);
342    bool        retval;
343
344    /*
345     * determine return value as a function of strategy, key and query.
346     *
347     * Use GIST_LEAF(entry) to know where you're called in the index tree,
348     * which comes handy when supporting the = operator for example (you could
349     * check for non empty union() in non-leaf nodes and equality in leaf
350     * nodes).
351     */
352
353    *recheck = true;        /* or false if check is exact */
354
355    PG_RETURN_BOOL(retval);
356}
357</programlisting>
358
359       Here, <varname>key</varname> is an element in the index and <varname>query</varname>
360       the value being looked up in the index. The <literal>StrategyNumber</literal>
361       parameter indicates which operator of your operator class is being
362       applied &mdash; it matches one of the operator numbers in the
363       <command>CREATE OPERATOR CLASS</command> command.
364      </para>
365
366      <para>
367       Depending on which operators you have included in the class, the data
368       type of <varname>query</varname> could vary with the operator, since it will
369       be whatever type is on the righthand side of the operator, which might
370       be different from the indexed data type appearing on the lefthand side.
371       (The above code skeleton assumes that only one type is possible; if
372       not, fetching the <varname>query</varname> argument value would have to depend
373       on the operator.)  It is recommended that the SQL declaration of
374       the <function>consistent</function> function use the opclass's indexed data
375       type for the <varname>query</varname> argument, even though the actual type
376       might be something else depending on the operator.
377      </para>
378
379     </listitem>
380    </varlistentry>
381
382    <varlistentry>
383     <term><function>union</function></term>
384     <listitem>
385      <para>
386       This method consolidates information in the tree.  Given a set of
387       entries, this function generates a new index entry that represents
388       all the given entries.
389      </para>
390
391      <para>
392        The <acronym>SQL</acronym> declaration of the function must look like this:
393
394<programlisting>
395CREATE OR REPLACE FUNCTION my_union(internal, internal)
396RETURNS storage_type
397AS 'MODULE_PATHNAME'
398LANGUAGE C STRICT;
399</programlisting>
400
401        And the matching code in the C module could then follow this skeleton:
402
403<programlisting>
404PG_FUNCTION_INFO_V1(my_union);
405
406Datum
407my_union(PG_FUNCTION_ARGS)
408{
409    GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
410    GISTENTRY  *ent = entryvec-&gt;vector;
411    data_type  *out,
412               *tmp,
413               *old;
414    int         numranges,
415                i = 0;
416
417    numranges = entryvec-&gt;n;
418    tmp = DatumGetDataType(ent[0].key);
419    out = tmp;
420
421    if (numranges == 1)
422    {
423        out = data_type_deep_copy(tmp);
424
425        PG_RETURN_DATA_TYPE_P(out);
426    }
427
428    for (i = 1; i &lt; numranges; i++)
429    {
430        old = out;
431        tmp = DatumGetDataType(ent[i].key);
432        out = my_union_implementation(out, tmp);
433    }
434
435    PG_RETURN_DATA_TYPE_P(out);
436}
437</programlisting>
438      </para>
439
440      <para>
441        As you can see, in this skeleton we're dealing with a data type
442        where <literal>union(X, Y, Z) = union(union(X, Y), Z)</literal>. It's easy
443        enough to support data types where this is not the case, by
444        implementing the proper union algorithm in this
445        <acronym>GiST</acronym> support method.
446      </para>
447
448      <para>
449        The result of the <function>union</function> function must be a value of the
450        index's storage type, whatever that is (it might or might not be
451        different from the indexed column's type).  The <function>union</function>
452        function should return a pointer to newly <function>palloc()</function>ed
453        memory. You can't just return the input value as-is, even if there is
454        no type change.
455      </para>
456
457      <para>
458       As shown above, the <function>union</function> function's
459       first <type>internal</type> argument is actually
460       a <structname>GistEntryVector</structname> pointer.  The second argument is a
461       pointer to an integer variable, which can be ignored.  (It used to be
462       required that the <function>union</function> function store the size of its
463       result value into that variable, but this is no longer necessary.)
464      </para>
465     </listitem>
466    </varlistentry>
467
468    <varlistentry>
469     <term><function>compress</function></term>
470     <listitem>
471      <para>
472       Converts a data item into a format suitable for physical storage in
473       an index page.
474       If the <function>compress</function> method is omitted, data items are stored
475       in the index without modification.
476      </para>
477
478      <para>
479        The <acronym>SQL</acronym> declaration of the function must look like this:
480
481<programlisting>
482CREATE OR REPLACE FUNCTION my_compress(internal)
483RETURNS internal
484AS 'MODULE_PATHNAME'
485LANGUAGE C STRICT;
486</programlisting>
487
488        And the matching code in the C module could then follow this skeleton:
489
490<programlisting>
491PG_FUNCTION_INFO_V1(my_compress);
492
493Datum
494my_compress(PG_FUNCTION_ARGS)
495{
496    GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
497    GISTENTRY  *retval;
498
499    if (entry-&gt;leafkey)
500    {
501        /* replace entry-&gt;key with a compressed version */
502        compressed_data_type *compressed_data = palloc(sizeof(compressed_data_type));
503
504        /* fill *compressed_data from entry-&gt;key ... */
505
506        retval = palloc(sizeof(GISTENTRY));
507        gistentryinit(*retval, PointerGetDatum(compressed_data),
508                      entry-&gt;rel, entry-&gt;page, entry-&gt;offset, FALSE);
509    }
510    else
511    {
512        /* typically we needn't do anything with non-leaf entries */
513        retval = entry;
514    }
515
516    PG_RETURN_POINTER(retval);
517}
518</programlisting>
519      </para>
520
521      <para>
522       You have to adapt <replaceable>compressed_data_type</replaceable> to the specific
523       type you're converting to in order to compress your leaf nodes, of
524       course.
525      </para>
526     </listitem>
527    </varlistentry>
528
529    <varlistentry>
530     <term><function>decompress</function></term>
531     <listitem>
532      <para>
533       Converts the stored representation of a data item into a format that
534       can be manipulated by the other GiST methods in the operator class.
535       If the <function>decompress</function> method is omitted, it is assumed that
536       the other GiST methods can work directly on the stored data format.
537       (<function>decompress</function> is not necessarily the reverse of
538       the <function>compress</function> method; in particular,
539       if <function>compress</function> is lossy then it's impossible
540       for <function>decompress</function> to exactly reconstruct the original
541       data.  <function>decompress</function> is not necessarily equivalent
542       to <function>fetch</function>, either, since the other GiST methods might not
543       require full reconstruction of the data.)
544      </para>
545
546      <para>
547        The <acronym>SQL</acronym> declaration of the function must look like this:
548
549<programlisting>
550CREATE OR REPLACE FUNCTION my_decompress(internal)
551RETURNS internal
552AS 'MODULE_PATHNAME'
553LANGUAGE C STRICT;
554</programlisting>
555
556        And the matching code in the C module could then follow this skeleton:
557
558<programlisting>
559PG_FUNCTION_INFO_V1(my_decompress);
560
561Datum
562my_decompress(PG_FUNCTION_ARGS)
563{
564    PG_RETURN_POINTER(PG_GETARG_POINTER(0));
565}
566</programlisting>
567
568        The above skeleton is suitable for the case where no decompression
569        is needed.  (But, of course, omitting the method altogether is even
570        easier, and is recommended in such cases.)
571      </para>
572     </listitem>
573    </varlistentry>
574
575    <varlistentry>
576     <term><function>penalty</function></term>
577     <listitem>
578      <para>
579       Returns a value indicating the <quote>cost</quote> of inserting the new
580       entry into a particular branch of the tree.  Items will be inserted
581       down the path of least <function>penalty</function> in the tree.
582       Values returned by <function>penalty</function> should be non-negative.
583       If a negative value is returned, it will be treated as zero.
584      </para>
585
586      <para>
587        The <acronym>SQL</acronym> declaration of the function must look like this:
588
589<programlisting>
590CREATE OR REPLACE FUNCTION my_penalty(internal, internal, internal)
591RETURNS internal
592AS 'MODULE_PATHNAME'
593LANGUAGE C STRICT;  -- in some cases penalty functions need not be strict
594</programlisting>
595
596        And the matching code in the C module could then follow this skeleton:
597
598<programlisting>
599PG_FUNCTION_INFO_V1(my_penalty);
600
601Datum
602my_penalty(PG_FUNCTION_ARGS)
603{
604    GISTENTRY  *origentry = (GISTENTRY *) PG_GETARG_POINTER(0);
605    GISTENTRY  *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
606    float      *penalty = (float *) PG_GETARG_POINTER(2);
607    data_type  *orig = DatumGetDataType(origentry-&gt;key);
608    data_type  *new = DatumGetDataType(newentry-&gt;key);
609
610    *penalty = my_penalty_implementation(orig, new);
611    PG_RETURN_POINTER(penalty);
612}
613</programlisting>
614
615        For historical reasons, the <function>penalty</function> function doesn't
616        just return a <type>float</type> result; instead it has to store the value
617        at the location indicated by the third argument.  The return
618        value per se is ignored, though it's conventional to pass back the
619        address of that argument.
620      </para>
621
622      <para>
623        The <function>penalty</function> function is crucial to good performance of
624        the index. It'll get used at insertion time to determine which branch
625        to follow when choosing where to add the new entry in the tree. At
626        query time, the more balanced the index, the quicker the lookup.
627      </para>
628     </listitem>
629    </varlistentry>
630
631    <varlistentry>
632     <term><function>picksplit</function></term>
633     <listitem>
634      <para>
635       When an index page split is necessary, this function decides which
636       entries on the page are to stay on the old page, and which are to move
637       to the new page.
638      </para>
639
640      <para>
641        The <acronym>SQL</acronym> declaration of the function must look like this:
642
643<programlisting>
644CREATE OR REPLACE FUNCTION my_picksplit(internal, internal)
645RETURNS internal
646AS 'MODULE_PATHNAME'
647LANGUAGE C STRICT;
648</programlisting>
649
650        And the matching code in the C module could then follow this skeleton:
651
652<programlisting>
653PG_FUNCTION_INFO_V1(my_picksplit);
654
655Datum
656my_picksplit(PG_FUNCTION_ARGS)
657{
658    GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
659    GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
660    OffsetNumber maxoff = entryvec-&gt;n - 1;
661    GISTENTRY  *ent = entryvec-&gt;vector;
662    int         i,
663                nbytes;
664    OffsetNumber *left,
665               *right;
666    data_type  *tmp_union;
667    data_type  *unionL;
668    data_type  *unionR;
669    GISTENTRY **raw_entryvec;
670
671    maxoff = entryvec-&gt;n - 1;
672    nbytes = (maxoff + 1) * sizeof(OffsetNumber);
673
674    v-&gt;spl_left = (OffsetNumber *) palloc(nbytes);
675    left = v-&gt;spl_left;
676    v-&gt;spl_nleft = 0;
677
678    v-&gt;spl_right = (OffsetNumber *) palloc(nbytes);
679    right = v-&gt;spl_right;
680    v-&gt;spl_nright = 0;
681
682    unionL = NULL;
683    unionR = NULL;
684
685    /* Initialize the raw entry vector. */
686    raw_entryvec = (GISTENTRY **) malloc(entryvec-&gt;n * sizeof(void *));
687    for (i = FirstOffsetNumber; i &lt;= maxoff; i = OffsetNumberNext(i))
688        raw_entryvec[i] = &amp;(entryvec-&gt;vector[i]);
689
690    for (i = FirstOffsetNumber; i &lt;= maxoff; i = OffsetNumberNext(i))
691    {
692        int         real_index = raw_entryvec[i] - entryvec-&gt;vector;
693
694        tmp_union = DatumGetDataType(entryvec-&gt;vector[real_index].key);
695        Assert(tmp_union != NULL);
696
697        /*
698         * Choose where to put the index entries and update unionL and unionR
699         * accordingly. Append the entries to either v-&gt;spl_left or
700         * v-&gt;spl_right, and care about the counters.
701         */
702
703        if (my_choice_is_left(unionL, curl, unionR, curr))
704        {
705            if (unionL == NULL)
706                unionL = tmp_union;
707            else
708                unionL = my_union_implementation(unionL, tmp_union);
709
710            *left = real_index;
711            ++left;
712            ++(v-&gt;spl_nleft);
713        }
714        else
715        {
716            /*
717             * Same on the right
718             */
719        }
720    }
721
722    v-&gt;spl_ldatum = DataTypeGetDatum(unionL);
723    v-&gt;spl_rdatum = DataTypeGetDatum(unionR);
724    PG_RETURN_POINTER(v);
725}
726</programlisting>
727
728       Notice that the <function>picksplit</function> function's result is delivered
729       by modifying the passed-in <structname>v</structname> structure.  The return
730       value per se is ignored, though it's conventional to pass back the
731       address of <structname>v</structname>.
732      </para>
733
734      <para>
735        Like <function>penalty</function>, the <function>picksplit</function> function
736        is crucial to good performance of the index.  Designing suitable
737        <function>penalty</function> and <function>picksplit</function> implementations
738        is where the challenge of implementing well-performing
739        <acronym>GiST</acronym> indexes lies.
740      </para>
741     </listitem>
742    </varlistentry>
743
744    <varlistentry>
745     <term><function>same</function></term>
746     <listitem>
747      <para>
748       Returns true if two index entries are identical, false otherwise.
749       (An <quote>index entry</quote> is a value of the index's storage type,
750       not necessarily the original indexed column's type.)
751      </para>
752
753      <para>
754        The <acronym>SQL</acronym> declaration of the function must look like this:
755
756<programlisting>
757CREATE OR REPLACE FUNCTION my_same(storage_type, storage_type, internal)
758RETURNS internal
759AS 'MODULE_PATHNAME'
760LANGUAGE C STRICT;
761</programlisting>
762
763        And the matching code in the C module could then follow this skeleton:
764
765<programlisting>
766PG_FUNCTION_INFO_V1(my_same);
767
768Datum
769my_same(PG_FUNCTION_ARGS)
770{
771    prefix_range *v1 = PG_GETARG_PREFIX_RANGE_P(0);
772    prefix_range *v2 = PG_GETARG_PREFIX_RANGE_P(1);
773    bool       *result = (bool *) PG_GETARG_POINTER(2);
774
775    *result = my_eq(v1, v2);
776    PG_RETURN_POINTER(result);
777}
778</programlisting>
779
780        For historical reasons, the <function>same</function> function doesn't
781        just return a Boolean result; instead it has to store the flag
782        at the location indicated by the third argument.  The return
783        value per se is ignored, though it's conventional to pass back the
784        address of that argument.
785      </para>
786     </listitem>
787    </varlistentry>
788
789    <varlistentry>
790     <term><function>distance</function></term>
791     <listitem>
792      <para>
793       Given an index entry <literal>p</literal> and a query value <literal>q</literal>,
794       this function determines the index entry's
795       <quote>distance</quote> from the query value.  This function must be
796       supplied if the operator class contains any ordering operators.
797       A query using the ordering operator will be implemented by returning
798       index entries with the smallest <quote>distance</quote> values first,
799       so the results must be consistent with the operator's semantics.
800       For a leaf index entry the result just represents the distance to
801       the index entry; for an internal tree node, the result must be the
802       smallest distance that any child entry could have.
803      </para>
804
805      <para>
806        The <acronym>SQL</acronym> declaration of the function must look like this:
807
808<programlisting>
809CREATE OR REPLACE FUNCTION my_distance(internal, data_type, smallint, oid, internal)
810RETURNS float8
811AS 'MODULE_PATHNAME'
812LANGUAGE C STRICT;
813</programlisting>
814
815        And the matching code in the C module could then follow this skeleton:
816
817<programlisting>
818PG_FUNCTION_INFO_V1(my_distance);
819
820Datum
821my_distance(PG_FUNCTION_ARGS)
822{
823    GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
824    data_type  *query = PG_GETARG_DATA_TYPE_P(1);
825    StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
826    /* Oid subtype = PG_GETARG_OID(3); */
827    /* bool *recheck = (bool *) PG_GETARG_POINTER(4); */
828    data_type  *key = DatumGetDataType(entry-&gt;key);
829    double      retval;
830
831    /*
832     * determine return value as a function of strategy, key and query.
833     */
834
835    PG_RETURN_FLOAT8(retval);
836}
837</programlisting>
838
839       The arguments to the <function>distance</function> function are identical to
840       the arguments of the <function>consistent</function> function.
841      </para>
842
843      <para>
844       Some approximation is allowed when determining the distance, so long
845       as the result is never greater than the entry's actual distance. Thus,
846       for example, distance to a bounding box is usually sufficient in
847       geometric applications.  For an internal tree node, the distance
848       returned must not be greater than the distance to any of the child
849       nodes. If the returned distance is not exact, the function must set
850       <literal>*recheck</literal> to true. (This is not necessary for internal tree
851       nodes; for them, the calculation is always assumed to be inexact.) In
852       this case the executor will calculate the accurate distance after
853       fetching the tuple from the heap, and reorder the tuples if necessary.
854      </para>
855
856      <para>
857       If the distance function returns <literal>*recheck = true</literal> for any
858       leaf node, the original ordering operator's return type must
859       be <type>float8</type> or <type>float4</type>, and the distance function's
860       result values must be comparable to those of the original ordering
861       operator, since the executor will sort using both distance function
862       results and recalculated ordering-operator results.  Otherwise, the
863       distance function's result values can be any finite <type>float8</type>
864       values, so long as the relative order of the result values matches the
865       order returned by the ordering operator.  (Infinity and minus infinity
866       are used internally to handle cases such as nulls, so it is not
867       recommended that <function>distance</function> functions return these values.)
868      </para>
869
870     </listitem>
871    </varlistentry>
872
873    <varlistentry>
874     <term><function>fetch</function></term>
875     <listitem>
876      <para>
877       Converts the compressed index representation of a data item into the
878       original data type, for index-only scans. The returned data must be an
879       exact, non-lossy copy of the originally indexed value.
880      </para>
881
882      <para>
883        The <acronym>SQL</acronym> declaration of the function must look like this:
884
885<programlisting>
886CREATE OR REPLACE FUNCTION my_fetch(internal)
887RETURNS internal
888AS 'MODULE_PATHNAME'
889LANGUAGE C STRICT;
890</programlisting>
891
892        The argument is a pointer to a <structname>GISTENTRY</structname> struct. On
893        entry, its <structfield>key</structfield> field contains a non-NULL leaf datum in
894        compressed form. The return value is another <structname>GISTENTRY</structname>
895        struct, whose <structfield>key</structfield> field contains the same datum in its
896        original, uncompressed form. If the opclass's compress function does
897        nothing for leaf entries, the <function>fetch</function> method can return the
898        argument as-is.  Or, if the opclass does not have a compress function,
899        the <function>fetch</function> method can be omitted as well, since it would
900        necessarily be a no-op.
901       </para>
902
903       <para>
904        The matching code in the C module could then follow this skeleton:
905
906<programlisting>
907PG_FUNCTION_INFO_V1(my_fetch);
908
909Datum
910my_fetch(PG_FUNCTION_ARGS)
911{
912    GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
913    input_data_type *in = DatumGetPointer(entry->key);
914    fetched_data_type *fetched_data;
915    GISTENTRY  *retval;
916
917    retval = palloc(sizeof(GISTENTRY));
918    fetched_data = palloc(sizeof(fetched_data_type));
919
920    /*
921     * Convert 'fetched_data' into the a Datum of the original datatype.
922     */
923
924    /* fill *retval from fetched_data. */
925    gistentryinit(*retval, PointerGetDatum(converted_datum),
926                  entry->rel, entry->page, entry->offset, FALSE);
927
928    PG_RETURN_POINTER(retval);
929}
930</programlisting>
931      </para>
932
933      <para>
934       If the compress method is lossy for leaf entries, the operator class
935       cannot support index-only scans, and must not define
936       a <function>fetch</function> function.
937      </para>
938
939     </listitem>
940    </varlistentry>
941  </variablelist>
942
943  <para>
944   All the GiST support methods are normally called in short-lived memory
945   contexts; that is, <varname>CurrentMemoryContext</varname> will get reset after
946   each tuple is processed.  It is therefore not very important to worry about
947   pfree'ing everything you palloc.  However, in some cases it's useful for a
948   support method to cache data across repeated calls.  To do that, allocate
949   the longer-lived data in <literal>fcinfo-&gt;flinfo-&gt;fn_mcxt</literal>, and
950   keep a pointer to it in <literal>fcinfo-&gt;flinfo-&gt;fn_extra</literal>.  Such
951   data will survive for the life of the index operation (e.g., a single GiST
952   index scan, index build, or index tuple insertion).  Be careful to pfree
953   the previous value when replacing a <literal>fn_extra</literal> value, or the leak
954   will accumulate for the duration of the operation.
955  </para>
956
957</sect1>
958
959<sect1 id="gist-implementation">
960 <title>Implementation</title>
961
962 <sect2 id="gist-buffering-build">
963  <title>GiST Buffering Build</title>
964  <para>
965   Building large GiST indexes by simply inserting all the tuples tends to be
966   slow, because if the index tuples are scattered across the index and the
967   index is large enough to not fit in cache, the insertions need to perform
968   a lot of random I/O.  Beginning in version 9.2, PostgreSQL supports a more
969   efficient method to build GiST indexes based on buffering, which can
970   dramatically reduce the number of random I/Os needed for non-ordered data
971   sets. For well-ordered data sets the benefit is smaller or non-existent,
972   because only a small number of pages receive new tuples at a time, and
973   those pages fit in cache even if the index as whole does not.
974  </para>
975
976  <para>
977   However, buffering index build needs to call the <function>penalty</function>
978   function more often, which consumes some extra CPU resources. Also, the
979   buffers used in the buffering build need temporary disk space, up to
980   the size of the resulting index. Buffering can also influence the quality
981   of the resulting index, in both positive and negative directions. That
982   influence depends on various factors, like the distribution of the input
983   data and the operator class implementation.
984  </para>
985
986  <para>
987   By default, a GiST index build switches to the buffering method when the
988   index size reaches <xref linkend="guc-effective-cache-size"/>. It can
989   be manually turned on or off by the <literal>buffering</literal> parameter
990   to the CREATE INDEX command. The default behavior is good for most cases,
991   but turning buffering off might speed up the build somewhat if the input
992   data is ordered.
993  </para>
994
995 </sect2>
996</sect1>
997
998<sect1 id="gist-examples">
999 <title>Examples</title>
1000
1001 <para>
1002  The <productname>PostgreSQL</productname> source distribution includes
1003  several examples of index methods implemented using
1004  <acronym>GiST</acronym>.  The core system currently provides text search
1005  support (indexing for <type>tsvector</type> and <type>tsquery</type>) as well as
1006  R-Tree equivalent functionality for some of the built-in geometric data types
1007  (see <filename>src/backend/access/gist/gistproc.c</filename>).  The following
1008  <filename>contrib</filename> modules also contain <acronym>GiST</acronym>
1009  operator classes:
1010
1011 <variablelist>
1012  <varlistentry>
1013   <term><filename>btree_gist</filename></term>
1014   <listitem>
1015    <para>B-tree equivalent functionality for several data types</para>
1016   </listitem>
1017  </varlistentry>
1018
1019  <varlistentry>
1020   <term><filename>cube</filename></term>
1021   <listitem>
1022    <para>Indexing for multidimensional cubes</para>
1023   </listitem>
1024  </varlistentry>
1025
1026  <varlistentry>
1027   <term><filename>hstore</filename></term>
1028   <listitem>
1029    <para>Module for storing (key, value) pairs</para>
1030   </listitem>
1031  </varlistentry>
1032
1033  <varlistentry>
1034   <term><filename>intarray</filename></term>
1035   <listitem>
1036    <para>RD-Tree for one-dimensional array of int4 values</para>
1037   </listitem>
1038  </varlistentry>
1039
1040  <varlistentry>
1041   <term><filename>ltree</filename></term>
1042   <listitem>
1043    <para>Indexing for tree-like structures</para>
1044   </listitem>
1045  </varlistentry>
1046
1047  <varlistentry>
1048   <term><filename>pg_trgm</filename></term>
1049   <listitem>
1050    <para>Text similarity using trigram matching</para>
1051   </listitem>
1052  </varlistentry>
1053
1054  <varlistentry>
1055   <term><filename>seg</filename></term>
1056   <listitem>
1057    <para>Indexing for <quote>float ranges</quote></para>
1058   </listitem>
1059  </varlistentry>
1060 </variablelist>
1061 </para>
1062
1063</sect1>
1064
1065</chapter>
1066