<!--
$Header: /cvsroot/pgsql/doc/src/sgml/xindex.sgml,v 1.30 2003/04/13 09:57:35 petere Exp $
-->

<sect1 id="xindex">
 <title>Interfacing Extensions To Indexes</title>

  <para>
   The procedures described thus far let you define new types, new
   functions, and new operators. However, we cannot yet define an
   index on a column of a new data type.  To do this, we must define an
   <firstterm>operator class</> for the new data type.  Later in this
   section, we will illustrate this concept in an example: a new
   operator class for the B-tree index method that stores and sorts
   complex numbers in ascending absolute value order.
  </para>

  <note>
   <para>
    Prior to <productname>PostgreSQL</productname> release 7.3, it was
    necessary to make manual additions to the system catalogs
    <classname>pg_amop</>, <classname>pg_amproc</>, and
    <classname>pg_opclass</> in order to create a user-defined
    operator class.  That approach is now deprecated in favor of
    using <command>CREATE OPERATOR CLASS</>, which is a much simpler
    and less error-prone way of creating the necessary catalog entries.
   </para>
  </note>

 <sect2 id="xindex-im">
  <title>Index Methods and Operator Classes</title>

  <para>
   The <classname>pg_am</classname> table contains one row for every
   index method (internally known as access method).  Support for
   regular access to tables is built into
   <productname>PostgreSQL</productname>, but all index methods are
   described in <classname>pg_am</classname>.  It is possible to add a
   new index method by defining the required interface routines and
   then creating a row in <classname>pg_am</classname> --- but that is
   far beyond the scope of this chapter.
  </para>

  <para>
   The routines for an index method do not directly know anything
   about the data types that the index method will operate on.  Instead, an
   <firstterm>operator class</> identifies the set of operations that the
   index method needs to use to work with a particular data type.
   Operator classes are so called because one thing they specify is the set
   of <literal>WHERE</>-clause operators that can be used with an index (i.e., can be
   converted into an index-scan qualification).  An operator class may also
   specify some <firstterm>support procedures</> that are needed by the
   internal operations of the index method, but do not directly
   correspond to any <literal>WHERE</>-clause operator that can be used with the index.
  </para>

  <para>
   It is possible to define multiple operator classes for the same
   data type and index method.  By doing this, multiple
   sets of indexing semantics can be defined for a single data type.
   For example, a B-tree index requires a sort ordering to be defined
   for each data type it works on.
   It might be useful for a complex-number data type
   to have one B-tree operator class that sorts the data by complex
   absolute value, another that sorts by real part, and so on.
   Typically, one of the operator classes will be deemed most commonly
   useful and will be marked as the default operator class for that
   data type and index method.
  </para>

  <para>
   The same operator class name
   can be used for several different index methods (for example, both B-tree
   and hash index methods have operator classes named
   <literal>oid_ops</literal>), but each such class is an independent
   entity and must be defined separately.
  </para>
 </sect2>

 <sect2 id="xindex-strategies">
  <title>Index Method Strategies</title>

  <para>
   The operators associated with an operator class are identified by
   <quote>strategy numbers</>, which serve to identify the semantics of
   each operator within the context of its operator class.
   For example, B-trees impose a strict ordering on keys, lesser to greater,
   and so operators like <quote>less than</> and <quote>greater than or equal
   to</> are interesting with respect to a B-tree.
   Because
   <productname>PostgreSQL</productname> allows the user to define operators,
   <productname>PostgreSQL</productname> cannot look at the name of an operator
   (e.g., <literal>&lt;</> or <literal>&gt;=</>) and tell what kind of
   comparison it is.  Instead, the index method defines a set of
   <quote>strategies</>, which can be thought of as generalized operators.
   Each operator class specifies which actual operator corresponds to each
   strategy for a particular data type and interpretation of the index
   semantics.
  </para>

  <para>
   The B-tree index method defines five strategies, shown in <xref
   linkend="xindex-btree-strat-table">.
  </para>

   <table tocentry="1" id="xindex-btree-strat-table">
    <title>B-tree Strategies</title>
    <tgroup cols="2">
     <thead>
      <row>
       <entry>Operation</entry>
       <entry>Strategy Number</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>less than</entry>
       <entry>1</entry>
      </row>
      <row>
       <entry>less than or equal</entry>
       <entry>2</entry>
      </row>
      <row>
       <entry>equal</entry>
       <entry>3</entry>
      </row>
      <row>
       <entry>greater than or equal</entry>
       <entry>4</entry>
      </row>
      <row>
       <entry>greater than</entry>
       <entry>5</entry>
      </row>
     </tbody>
    </tgroup>
   </table>

  <para>
   Hash indexes express only bitwise equality, and so they use only one
   strategy, shown in <xref linkend="xindex-hash-strat-table">.
  </para>

   <table tocentry="1" id="xindex-hash-strat-table">
    <title>Hash Strategies</title>
    <tgroup cols="2">
     <thead>
      <row>
       <entry>Operation</entry>
       <entry>Strategy Number</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>equal</entry>
       <entry>1</entry>
      </row>
     </tbody>
    </tgroup>
   </table>

  <para>
   R-tree indexes express rectangle-containment relationships.
   They use eight strategies, shown in <xref linkend="xindex-rtree-strat-table">.
  </para>

   <table tocentry="1" id="xindex-rtree-strat-table">
    <title>R-tree Strategies</title>
    <tgroup cols="2">
     <thead>
      <row>
       <entry>Operation</entry>
       <entry>Strategy Number</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>left of</entry>
       <entry>1</entry>
      </row>
      <row>
       <entry>left of or overlapping</entry>
       <entry>2</entry>
      </row>
      <row>
       <entry>overlapping</entry>
       <entry>3</entry>
      </row>
      <row>
       <entry>right of or overlapping</entry>
       <entry>4</entry>
      </row>
      <row>
       <entry>right of</entry>
       <entry>5</entry>
      </row>
      <row>
       <entry>same</entry>
       <entry>6</entry>
      </row>
      <row>
       <entry>contains</entry>
       <entry>7</entry>
      </row>
      <row>
       <entry>contained by</entry>
       <entry>8</entry>
      </row>
     </tbody>
    </tgroup>
   </table>

  <para>
   GiST indexes are even more flexible: they do not have a fixed set of
   strategies at all.  Instead, the <quote>consistency</> support routine
   of each particular GiST operator class interprets the strategy numbers
   however it likes.
  </para>

  <para>
   Note that all strategy operators return Boolean values.  In
   practice, all operators defined as index method strategies must
   return type <type>boolean</type>, since they must appear at the top
   level of a <literal>WHERE</> clause to be used with an index.
  </para>

  <para>
   By the way, the <structfield>amorderstrategy</structfield> column
   in <classname>pg_am</> tells whether
   the index method supports ordered scans.  Zero means it doesn't; if it
   does, <structfield>amorderstrategy</structfield> is the strategy
   number that corresponds to the ordering operator.  For example, B-tree
   has <structfield>amorderstrategy</structfield> = 1, which is its
   <quote>less than</quote> strategy number.
  </para>
 </sect2>

 <sect2 id="xindex-support">
  <title>Index Method Support Routines</title>

  <para>
   Strategies aren't usually enough information for the system to figure
   out how to use an index.  In practice, the index methods require
   additional support routines in order to work. For example, the B-tree
   index method must be able to compare two keys and determine whether one
   is greater than, equal to, or less than the other.  Similarly, the
   R-tree index method must be able to compute
   intersections,  unions, and sizes of rectangles.  These
   operations do not correspond to operators used in qualifications in
   SQL commands;  they are administrative routines used by
   the index methods, internally.
  </para>

  <para>
   Just as with strategies, the operator class identifies which specific
   functions should play each of these roles for a given data type and
   semantic interpretation.  The index method defines the set
   of functions it needs, and the operator class identifies the correct
   functions to use by assigning them to the <quote>support function numbers</>.
  </para>

  <para>
   B-trees require a single support function, shown in <xref
   linkend="xindex-btree-support-table">.
  </para>

   <table tocentry="1" id="xindex-btree-support-table">
    <title>B-tree Support Functions</title>
    <tgroup cols="2">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Support Number</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>
   Compare two keys and return an integer less than zero, zero, or
   greater than zero, indicating whether the first key is less than, equal to,
   or greater than the second.
       </entry>
       <entry>1</entry>
      </row>
     </tbody>
    </tgroup>
   </table>

  <para>
   Hash indexes likewise require one support function, shown in <xref
   linkend="xindex-hash-support-table">.
  </para>

   <table tocentry="1" id="xindex-hash-support-table">
    <title>Hash Support Functions</title>
    <tgroup cols="2">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Support Number</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>Compute the hash value for a key</entry>
       <entry>1</entry>
      </row>
     </tbody>
    </tgroup>
   </table>

  <para>
   R-tree indexes require three support functions,
   shown in <xref linkend="xindex-rtree-support-table">.
  </para>

   <table tocentry="1" id="xindex-rtree-support-table">
    <title>R-tree Support Functions</title>
    <tgroup cols="2">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Support Number</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>union</entry>
       <entry>1</entry>
      </row>
      <row>
       <entry>intersection</entry>
       <entry>2</entry>
      </row>
      <row>
       <entry>size</entry>
       <entry>3</entry>
      </row>
     </tbody>
    </tgroup>
   </table>

  <para>
   GiST indexes require seven support functions,
   shown in <xref linkend="xindex-gist-support-table">.
  </para>

   <table tocentry="1" id="xindex-gist-support-table">
    <title>GiST Support Functions</title>
    <tgroup cols="2">
     <thead>
      <row>
       <entry>Function</entry>
       <entry>Support Number</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>consistent</entry>
       <entry>1</entry>
      </row>
      <row>
       <entry>union</entry>
       <entry>2</entry>
      </row>
      <row>
       <entry>compress</entry>
       <entry>3</entry>
      </row>
      <row>
       <entry>decompress</entry>
       <entry>4</entry>
      </row>
      <row>
       <entry>penalty</entry>
       <entry>5</entry>
      </row>
      <row>
       <entry>picksplit</entry>
       <entry>6</entry>
      </row>
      <row>
       <entry>equal</entry>
       <entry>7</entry>
      </row>
     </tbody>
    </tgroup>
   </table>

  <para>
   Unlike strategy operators, support functions return whichever data
   type the particular index method expects, for example in the case
   of the comparison function for B-trees, a signed integer.
  </para>
 </sect2>

 <sect2 id="xindex-example">
  <title>An Example</title>

  <para>
   Now that we have seen the ideas, here is the promised example of
   creating a new operator class.  The operator class encapsulates
   operators that sort complex numbers in absolute value order, so we
   choose the name <literal>complex_abs_ops</literal>.  First, we need
   a set of operators.  The procedure for defining operators was
   discussed in <xref linkend="xoper">.  For an operator class on
   B-trees, the operators we require are:

   <itemizedlist spacing="compact">
    <listitem><simpara>absolute-value less-than (strategy 1)</></>
    <listitem><simpara>absolute-value less-than-or-equal (strategy 2)</></>
    <listitem><simpara>absolute-value equal (strategy 3)</></>
    <listitem><simpara>absolute-value greater-than-or-equal (strategy 4)</></>
    <listitem><simpara>absolute-value greater-than (strategy 5)</></>
   </itemizedlist>
  </para>

  <para>
   The C code for the equality operator look like this:

<programlisting>
#define Mag(c) ((c)-&gt;x*(c)-&gt;x + (c)-&gt;y*(c)-&gt;y)

bool
complex_abs_eq(Complex *a, Complex *b)
{
    double amag = Mag(a), bmag = Mag(b);
    return (amag == bmag);
}
</programlisting>
   The other four operators are very similar.  You can find their code
   in <filename>src/tutorial/complex.c</filename> and
   <filename>src/tutorial/complex.sql</filename> in the source
   distribution.
  </para>

  <para>
   Now declare the functions and the operators based on the functions:
<programlisting>
CREATE FUNCTION complex_abs_eq(complex, complex) RETURNS boolean
    AS '<replaceable>filename</replaceable>', 'complex_abs_eq'
    LANGUAGE C;

CREATE OPERATOR = (
    leftarg = complex,
    rightarg = complex,
    procedure = complex_abs_eq,
    restrict = eqsel,
    join = eqjoinsel
);
</programlisting>
   It is important to specify the restriction and join selectivity
   functions, otherwise the optimizer will be unable to make effective
   use of the index.  Note that there less-than, equal, and
   greater-than cases should use different selectivity functions.
  </para>

  <para>
   Other things worth noting are happening here:

  <itemizedlist>
   <listitem>
    <para>
     There can only be one operator named, say, <literal>=</literal>
     and taking type <type>complex</type> for both operands.  In this
     case we don't have any other operator <literal>=</literal> for
     <type>complex</type>, but if we were building a practical data
     type we'd probably want <literal>=</literal> to be the ordinary
     equality operation for complex numbers (and not the equality of
     the absolute values).  In that case, we'd need to use some other
     operator name for <function>complex_abs_eq</>.
    </para>
   </listitem>

   <listitem>
    <para>
     Although <productname>PostgreSQL</productname> can cope with
     functions having the same name as long as they have different
     argument data types, C can only cope with one global function
     having a given name.  So we shouldn't name the C function
     something simple like <filename>abs_eq</filename>.  Usually it's
     a good practice to include the data type name in the C function
     name, so as not to conflict with functions for other data types.
    </para>
   </listitem>

   <listitem>
    <para>
     We could have made the <productname>PostgreSQL</productname> name
     of the function <filename>abs_eq</filename>, relying on
     <productname>PostgreSQL</productname> to distinguish it by
     argument data types from any other
     <productname>PostgreSQL</productname> function of the same name.
     To keep the example simple, we make the function have the same
     names at the C level and <productname>PostgreSQL</productname>
     level.
    </para>
   </listitem>
  </itemizedlist>
  </para>

  <para>
   The next step is the registration of the support routine required
   by B-trees.  The example C code that implements this is in the same
   file that contains the operator functions.  This is how we declare
   the function:

<programlisting>
CREATE FUNCTION complex_abs_cmp(complex, complex)
    RETURNS integer
    AS '<replaceable>filename</replaceable>'
    LANGUAGE C;
</programlisting>
  </para>

  <para>
   Now that we have the required operators and support routine,
   we can finally create the operator class:

<programlisting>
CREATE OPERATOR CLASS complex_abs_ops
    DEFAULT FOR TYPE complex USING btree AS
        OPERATOR        1       &lt; ,
        OPERATOR        2       &lt;= ,
        OPERATOR        3       = ,
        OPERATOR        4       &gt;= ,
        OPERATOR        5       &gt; ,
        FUNCTION        1       complex_abs_cmp(complex, complex);
</programlisting>
  </para>

  <para>
   And we're done!  It should now be possible to create
   and use B-tree indexes on <type>complex</type> columns.
  </para>

  <para>
   We could have written the operator entries more verbosely, as in
<programlisting>
        OPERATOR        1       &lt; (complex, complex) ,
</programlisting>
   but there is no need to do so when the operators take the same data type
   we are defining the operator class for.
  </para>

  <para>
   The above example assumes that you want to make this new operator class the
   default B-tree operator class for the <type>complex</type> data type.
   If you don't, just leave out the word <literal>DEFAULT</>.
  </para>
 </sect2>

 <sect2 id="xindex-opclass-features">
  <title>Special Features of Operator Classes</title>

  <para>
   There are two special features of operator classes that we have
   not discussed yet, mainly because they are not very useful
   with the default B-tree index method.
  </para>

  <para>
   Normally, declaring an operator as a member of an operator class means
   that the index method can retrieve exactly the set of rows
   that satisfy a <literal>WHERE</> condition using the operator.  For example,
<programlisting>
SELECT * FROM table WHERE integer_column &lt; 4;
</programlisting>
   can be satisfied exactly by a B-tree index on the integer column.
   But there are cases where an index is useful as an inexact guide to
   the matching rows.  For example, if an R-tree index stores only
   bounding boxes for objects, then it cannot exactly satisfy a <literal>WHERE</>
   condition that tests overlap between nonrectangular objects such as
   polygons.  Yet we could use the index to find objects whose bounding
   box overlaps the bounding box of the target object, and then do the
   exact overlap test only on the objects found by the index.  If this
   scenario applies, the index is said to be <quote>lossy</> for the
   operator, and we add <literal>RECHECK</> to the <literal>OPERATOR</> clause
   in the <command>CREATE OPERATOR CLASS</> command.
   <literal>RECHECK</> is valid if the index is guaranteed to return
   all the required rows, plus perhaps some additional rows, which
   can be eliminated by performing the original operator invocation.
  </para>

  <para>
   Consider again the situation where we are storing in the index only
   the bounding box of a complex object such as a polygon.  In this
   case there's not much value in storing the whole polygon in the index
   entry --- we may as well store just a simpler object of type
   <type>box</>.  This situation is expressed by the <literal>STORAGE</>
   option in <command>CREATE OPERATOR CLASS</>: we'd write something like

<programlisting>
CREATE OPERATOR CLASS polygon_ops
    DEFAULT FOR TYPE polygon USING gist AS
        ...
        STORAGE box;
</programlisting>

   At present, only the GiST index method supports a
   <literal>STORAGE</> type that's different from the column data type.
   The GiST <literal>compress</> and <literal>decompress</> support
   routines must deal with data-type conversion when <literal>STORAGE</>
   is used.
  </para>
 </sect2>

</sect1>

<!-- Keep this comment at the end of the file
Local variables:
mode:sgml
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:("/usr/lib/sgml/catalog")
sgml-local-ecat-files:nil
End:
-->
