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