<?xml version="1.0" encoding="UTF-8"?>
<sect1 id="using_postgis_dbmanagement">
  <title>Data Management</title>

  <sect2 id="RefObject">
	<title>GIS Objects</title>

	<para>The GIS objects supported by PostGIS are a superset of the "Simple
	Features" standard defined by the OpenGIS Consortium (OGC).
	PostGIS supports all the objects and functions specified in the OGC
	"Simple Features for SQL" specification (SFS).</para>

	<para>PostGIS extends the standard with support for embedded SRID information.</para>

	<sect3 id="OpenGISWKBWKT">
	  <title>OpenGIS WKB and WKT</title>

	  <para>The OpenGIS specification defines two standard ways of expressing
	  spatial objects: the Well-Known Text (WKT) form and the Well-Known
	  Binary (WKB) form. Both WKT and WKB include information about the type
	  of the object and the coordinates which form the object.</para>

	  <para>Examples of the text representations (WKT) of the spatial objects
	  of the features are as follows:</para>

	  <itemizedlist>
		<listitem>
		  <para>POINT(0 0)</para>
		</listitem>

		<listitem>
		  <para>POINT Z (0 0 0)</para>
		</listitem>

		<listitem>
		  <para>POINT ZM (0 0 0 0)</para>
		</listitem>

		<listitem>
		  <para>LINESTRING(0 0,1 1,1 2)</para>
		</listitem>

		<listitem>
		  <para>POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))</para>
		</listitem>

		<listitem>
		  <para>MULTIPOINT((0 0),(1 2))</para>
		</listitem>

		<listitem>
		  <para>MULTIPOINT Z ((0 0 0),(1 2 3))</para>
		</listitem>

		<listitem>
		  <para>MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))</para>
		</listitem>

		<listitem>
		  <para>MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)),
		  ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))</para>
		</listitem>

		<listitem>
		  <para>GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))</para>
		</listitem>
	  </itemizedlist>

	  <para>The OpenGIS specification also requires that the internal storage
	  format of spatial objects include a spatial referencing system
	  identifier (SRID). The SRID is required when creating spatial objects
	  for insertion into the database.</para>

	  <para>Input/Output of these formats are available using the following
	  interfaces:</para>

	  <programlisting>bytea WKB = ST_AsBinary(geometry);
text WKT = ST_AsText(geometry);
geometry = ST_GeomFromWKB(bytea WKB, SRID);
geometry = ST_GeometryFromText(text WKT, SRID);</programlisting>

	  <para>For example, a valid insert statement to create and insert an OGC
	  spatial object would be:</para>

	  <programlisting>INSERT INTO geotable ( the_geom, the_name )
  VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'A Place');</programlisting>
	</sect3>

	<sect3 id="EWKB_EWKT">
	  <title>PostGIS EWKB, EWKT and Canonical Forms</title>

		<para>First OpenGIS specifications (prior to 1.2.0) only support 2D geometries,
		and the associated SRID is *never* embedded in the input/output representations.</para>

		<para>Even though the last OpenGIS specification 1.2.1 supports 3DM and 3DZ coordinates
		specifing ZM qualifiers, it does not include yet the associated SRID in the
		input/output representations.</para>

		<para>PostGIS extended formats add 3DM, 3DZ, 4D coordinates support and embedded
		SRID information. However, PostGIS EWKB/EWKT outputs have several peculiarities:</para>

		<itemizedlist>
			<listitem>
				<para>For 3DZ geometries they will drop the Z qualifier:</para>
				<para>OpenGIS: POINT Z (1 2 3)</para>
				<para>EWKB/EWKT: POINT(1 2 3)</para>
			</listitem>
			<listitem>
				<para>For 3DM geometries they will keep the M qualifier:</para>
				<para>OpenGIS: POINT M (1 2 3)</para>
				<para>EWKB/EWKT: POINTM(1 2 3)</para>
			</listitem>
			<listitem>
				<para>For 4D geometries they will drop the ZM qualifiers:</para>
				<para>OpenGIS: POINT ZM (1 2 3 4)</para>
				<para>EWKB/EWKT: POINT(1 2 3 4)</para>
			</listitem>
		</itemizedlist>

		<para>By doing this, PostGIS EWKB/EWKT avoids over-specifying dimensionality and a whole
		categories of potential errors that ISO admits, e.g.:</para>

		<itemizedlist>
			<listitem>
				<para>POINT ZM (1 1)</para>
			</listitem>
			<listitem>
				<para>POINT ZM (1 1 1)</para>
			</listitem>
			<listitem>
				<para>POINT (1 1 1 1)</para>
			</listitem>
		</itemizedlist>

		<caution>
			<para>PostGIS extended formats are currently superset of the OGC one (every valid WKB/WKT is a valid EWKB/EWKT)
			but this might vary in the future, specifically if OGC comes out with a new format conflicting with our
			extensions. Thus you SHOULD NOT rely on this feature!</para>
		</caution>

	  <para>Examples of the text representations (EWKT) of the extended
	  spatial objects of the features are as follows.</para>

	  <itemizedlist>
		<listitem>
		  <para>POINT(0 0 0) -- XYZ</para>
		</listitem>

		<listitem>
		  <para>SRID=32632;POINT(0 0) -- XY with SRID</para>
		</listitem>

		<listitem>
		  <para>POINTM(0 0 0) -- XYM</para>
		</listitem>

		<listitem>
		  <para>POINT(0 0 0 0) -- XYZM</para>
		</listitem>

		<listitem>
		  <para>SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM with SRID</para>
		</listitem>

		<listitem>
		  <para>MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4
		  1))</para>
		</listitem>

		<listitem>
		  <para>POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2
		  0,1 1 0))</para>
		</listitem>

		<listitem>
		  <para>MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2
		  0,1 2 0,1 1 0)),((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))</para>
		</listitem>

		<listitem>
		  <para>GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )</para>
		</listitem>

		<listitem>
		    <para>MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )</para>
		</listitem>

		<listitem>
		  <para>POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),  ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),  ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )</para>
		</listitem>

		<listitem>
		  <para>TRIANGLE ((0 0, 0 9, 9 0, 0 0))</para>
		</listitem>

		<listitem>
		  <para>TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)),
		  ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )</para>
		</listitem>
	  </itemizedlist>

	  <para>Conversion between these formats is available using the following interfaces:</para>

	  <programlisting>bytea EWKB = ST_AsEWKB(geometry);
text EWKT = ST_AsEWKT(geometry);
geometry = ST_GeomFromEWKB(bytea EWKB);
geometry = ST_GeomFromEWKT(text EWKT);</programlisting>

	  <para>For example, a valid insert statement to create and insert a
	  PostGIS spatial object would be:</para>

	  <programlisting>INSERT INTO geotable ( the_geom, the_name )
  VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )</programlisting>

	  <para>The "canonical forms" of a PostgreSQL type are the representations
	  you get with a simple query (without any function call) and the one
	  which is guaranteed to be accepted with a simple insert, update or copy.
	  For the PostGIS 'geometry' type these are:
		<programlisting>- Output
  - binary: EWKB
	ascii: HEXEWKB (EWKB in hex form)
- Input
  - binary: EWKB
	ascii: HEXEWKB|EWKT </programlisting></para>

	  <para>For example this statement reads EWKT and returns HEXEWKB in the
	  process of canonical ascii input/output:</para>

	  <programlisting>=# SELECT 'SRID=4;POINT(0 0)'::geometry;

geometry
----------------------------------------------------
01010000200400000000000000000000000000000000000000
(1 row)</programlisting>
	</sect3>
	<sect3 id="SQL_MM_Part3">
	  <title>SQL-MM Part 3</title>

	  <para>The SQL Multimedia Applications Spatial specification extends the
	  simple features for SQL spec by defining a number of circularly
	  interpolated curves.</para>

	  <para>The SQL-MM definitions include 3DM, 3DZ and 4D coordinates, but do
	  not allow the embedding of SRID information.</para>

	  <para>The Well-Known Text extensions are not yet fully supported.
	  Examples of some simple curved geometries are shown below:</para>

	  <itemizedlist>
		<listitem>
		  <para>CIRCULARSTRING(0 0, 1 1, 1 0)</para>
		  <para>CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)</para>
		  <para>The CIRCULARSTRING is the basic curve type, similar to a
		  LINESTRING in the linear world.  A single segment required three
		  points, the start and end points (first and third) and any other
		  point on the arc.  The exception to this is for a closed circle,
		  where the start and end points are the same.  In this case the
		  second point MUST be the center of the arc, ie the opposite side of
		  the circle.  To chain arcs together, the last point of the previous
		  arc becomes the first point of the next arc, just like in
		  LINESTRING.  This means that a valid circular string must have an
		  odd number of points greater than 1.</para>
		</listitem>

		<listitem>
		  <para>COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))</para>
		  <para>A compound curve is a single, continuous curve that has both
		  curved (circular) segments and linear segments.  That means that
		  in addition to having well-formed components, the end point of
		  every component (except the last) must be coincident with the
		  start point of the following component.</para>
		</listitem>

		<listitem>
		  <para>CURVEPOLYGON(CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),(1 1, 3
		  3, 3 1, 1 1))</para>
		  <para>Example compound curve in a curve polygon:
				CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0,2 0, 2 1, 2 3, 4 3),(4 3, 4 5, 1 4, 0 0)),
					CIRCULARSTRING(1.7 1, 1.4 0.4, 1.6 0.4, 1.6 0.5, 1.7 1) )
		  </para>
		  <para>A CURVEPOLYGON is just like a polygon, with an outer ring
		  and zero or more inner rings.  The difference is that a ring can
		  take the form of a circular string, linear string or compound
		  string.</para>
		  <para>As of PostGIS 1.4 PostGIS supports compound curves in a curve polygon.</para>
		</listitem>

		<listitem>
		  <para>MULTICURVE((0 0, 5 5),CIRCULARSTRING(4 0, 4 4, 8 4))</para>
		  <para>The MULTICURVE is a collection of curves, which can include
		  linear strings, circular strings or compound strings.</para>
		</listitem>

		<listitem>
		  <para>MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0
		  0),(1 1, 3 3, 3 1, 1 1)),((10 10, 14 12, 11 10, 10 10),(11 11, 11.5
		  11, 11 11.5, 11 11)))</para>
		  <para>This is a collection of surfaces, which can be (linear)
		  polygons or curve polygons.</para>
		</listitem>
	  </itemizedlist>

	  <note>
		<para>All floating point comparisons within the SQL-MM implementation
		are performed to a specified tolerance, currently 1E-8.</para>
	  </note>
	</sect3>
  </sect2>
  <sect2 id="PostGIS_Geography">
	  <title>PostGIS Geography Type</title>

	  <para>The geography type provides native support for spatial features represented on "geographic" coordinates (sometimes called "geodetic" coordinates, or "lat/lon", or "lon/lat"). Geographic coordinates are spherical coordinates expressed in angular units (degrees). </para>

	  <para>The basis for the PostGIS geometry type is a plane. The shortest path between two points on the plane is a straight line. That means calculations on geometries (areas, distances, lengths, intersections, etc) can be calculated using cartesian mathematics and straight line vectors.</para>

	  <para>The basis for the PostGIS geographic type is a sphere. The shortest path between two points on the sphere is a great circle arc. That means that calculations on geographies (areas, distances, lengths, intersections, etc) must be calculated on the sphere, using more complicated mathematics. For more accurate measurements, the calculations must take the actual spheroidal shape of the world into account.</para>

	  <para>Because the underlying mathematics is much more complicated, there are fewer functions defined for the geography type than for the geometry type. Over time, as new algorithms are added, the capabilities of the geography type will expand.</para>

		<para>It uses a data type called <varname>geography</varname>. None of the GEOS functions support the <varname>geography</varname>
	  type. As a workaround one can convert back and forth between geometry and geography types.</para>

	  <para>Prior to PostGIS 2.2, the geography type only supported WGS 84 long lat (SRID:4326).
		For PostGIS 2.2 and above, any long/lat based spatial reference system defined in the <varname>spatial_ref_sys</varname> table can be used.
		You can even add your own custom spheroidal spatial reference system as described in <ulink url="http://www.bostongis.com/blog/index.php?/archives/266-geography-type-is-not-limited-to-earth.html">geography type is not limited to earth</ulink>.</para>

		<para>Regardless which spatial reference system you use, the units returned by the measurement (<xref linkend="ST_Distance" />, <xref linkend="ST_Length" />, <xref linkend="ST_Perimeter" />, <xref linkend="ST_Area" />) and for input of <xref linkend="ST_DWithin" /> are in meters.</para>

	  <para>The geography type uses the PostgreSQL typmod definition format so that a table with a geography field
			can be added in a single step.  All the standard OGC formats except for curves are supported.</para>

	<sect3 id="Geography_Basics">
		<title>Geography Basics</title>
		<para>The geography type does not support curves, TINS, or POLYHEDRALSURFACEs, but other geometry types are supported. Standard geometry type data will autocast to geography if it is of SRID 4326.  You can also use the EWKT and EWKB
			conventions to insert data.</para>

		<itemizedlist>
		<listitem>
		  <para>POINT: Creating a table with 2D point geography when srid is not specified defaults to 4326 WGS 84 long lat:</para>
		  <para><programlisting>CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT) );</programlisting></para>
		  <para>POINT: Creating a table with 2D point geography in NAD83 longlat:</para>
		  <para><programlisting>CREATE TABLE ptgeognad83(gid serial PRIMARY KEY, geog geography(POINT,4269) );</programlisting></para>
		  <para>Creating a table with z coordinate point and explicitly specifying srid</para>
		  <para><programlisting>CREATE TABLE ptzgeogwgs84(gid serial PRIMARY KEY, geog geography(POINTZ,4326) );</programlisting></para>
		</listitem>
		<listitem>
			<para>LINESTRING</para>
			<para><programlisting>CREATE TABLE lgeog(gid serial PRIMARY KEY, geog geography(LINESTRING) );</programlisting></para>
		</listitem>
		<listitem>
			<para>POLYGON</para>
			<para><programlisting>--polygon NAD 1927 long lat
CREATE TABLE lgeognad27(gid serial PRIMARY KEY, geog geography(POLYGON,4267) );</programlisting></para>
		</listitem>
		<listitem>
			<para>MULTIPOINT</para>
		</listitem>
		<listitem>
			<para>MULTILINESTRING</para>
		</listitem>
		<listitem>
			<para>MULTIPOLYGON</para>
		</listitem>
		<listitem>
			<para>GEOMETRYCOLLECTION</para>
		</listitem>
		<!-- TODO: Add other examples -->
		</itemizedlist>
		<para>The geography fields get registered in the <varname>geography_columns</varname> system view.</para>

		<para>Now, check the "geography_columns" view and see that your table is listed.</para>

		<para>You can create a new table with a GEOGRAPHY column using the CREATE TABLE syntax.</para>

		<para>
<programlisting>CREATE TABLE global_points (
    id SERIAL PRIMARY KEY,
    name VARCHAR(64),
    location GEOGRAPHY(POINT,4326)
  );</programlisting>
		</para>

		<para>Note that the location column has type GEOGRAPHY and that geography type supports two optional modifiers: a type modifier that restricts the kind of shapes and dimensions allowed in the column; an SRID modifier that restricts the coordinate reference identifier to a particular number.</para>
		<para>Allowable values for the type modifier are: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON. The modifier also supports dimensionality restrictions through suffixes: Z, M and ZM. So, for example a modifier of 'LINESTRINGM' would only allow line strings with three dimensions in, and would treat the third dimension as a measure.
		Similarly, 'POINTZM' would expect four dimensional data.</para>
		<para>If you do not specify an SRID, the SRID will default to 4326 WGS 84 long/lat will be used, and all calculations will proceed using WGS84.</para>
		<para>Once you have created your table, you can see it in the GEOGRAPHY_COLUMNS table:</para>
		<para><programlisting>
-- See the contents of the metadata view
SELECT * FROM geography_columns;</programlisting></para>

<para>You can insert data into the table the same as you would if it was using a GEOMETRY column:</para>

<para><programlisting>-- Add some data into the test table
INSERT INTO global_points (name, location) VALUES ('Town', 'SRID=4326;POINT(-110 30)');
INSERT INTO global_points (name, location) VALUES ('Forest', 'SRID=4326;POINT(-109 29)');
INSERT INTO global_points (name, location) VALUES ('London', 'SRID=4326;POINT(0 49)');</programlisting></para>

<para>Creating an index works the same as GEOMETRY.
	PostGIS will note that the column type is GEOGRAPHY and create an appropriate sphere-based index instead of the usual planar index used for GEOMETRY.</para>

<para><programlisting>-- Index the test table with a spherical index
  CREATE INDEX global_points_gix ON global_points USING GIST ( location );</programlisting>
</para>

<para>Query and measurement functions use units of meters. So distance parameters should be expressed in meters, and return values should be expected in meters (or square meters for areas).</para>

<para><programlisting>-- Show a distance query and note, London is outside the 1000km tolerance
  SELECT name FROM global_points WHERE ST_DWithin(location, 'SRID=4326;POINT(-110 29)'::geography, 1000000);</programlisting>
</para>

<para>You can see the power of GEOGRAPHY in action by calculating how close a plane flying from Seattle to London (LINESTRING(-122.33 47.606, 0.0 51.5)) comes to Reykjavik (POINT(-21.96 64.15)).</para>

<para><programlisting>-- Distance calculation using GEOGRAPHY (122.2km)
  SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)'::geography);</programlisting>
</para>

<para><programlisting>-- Distance calculation using GEOMETRY (13.3 "degrees")
  SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15)'::geometry);</programlisting>
</para>

<para>Testing different lon/lat projects.
Any long lat spatial reference system listed in <varname>spatial_ref_sys</varname> table is allowed.</para>
<para>	<programlisting>-- NAD 83 lon/lat
SELECT 'SRID=4269;POINT(-123 34)'::geography;
                    geography
----------------------------------------------------
 0101000020AD1000000000000000C05EC00000000000004140
(1 row)</programlisting>

<programlisting>-- NAD27 lon/lat
SELECT 'SRID=4267;POINT(-123 34)'::geography;

                    geography
----------------------------------------------------
 0101000020AB1000000000000000C05EC00000000000004140
(1 row)</programlisting>

<programlisting>-- NAD83 UTM zone meters, yields error since its a meter based projection
SELECT 'SRID=26910;POINT(-123 34)'::geography;

ERROR:  Only lon/lat coordinate systems are supported in geography.
LINE 1: SELECT 'SRID=26910;POINT(-123 34)'::geography;</programlisting></para>

<para>The GEOGRAPHY type calculates the true shortest distance over the sphere between Reykjavik and the great circle flight path between Seattle and London.</para>

<para> <ulink url="http://gc.kls2.com/cgi-bin/gc?PATH=SEA-LHR">Great Circle mapper</ulink>
The GEOMETRY type calculates a meaningless cartesian distance between Reykjavik and the straight line path from Seattle to London plotted on a flat map of the world. The nominal units of the result might be called "degrees", but the result doesn't correspond to any true angular difference between the points, so even calling them "degrees" is inaccurate.</para>
	</sect3>
	<sect3 id="PostGIS_GeographyVSGeometry">
	  <title>When to use Geography Data type over Geometry data type</title>
	  <para>The geography type allows you to store data in longitude/latitude coordinates, but at a cost: there are fewer functions defined on GEOGRAPHY than there are on GEOMETRY; those functions that are defined take more CPU time to execute.</para>
	  <para>The type you choose should be conditioned on the expected working area of the application you are building. Will your data span the globe or a large continental area, or is it local to a state, county or municipality? </para>
	  <itemizedlist>
		<listitem><para>If your data is contained in a small area, you might find that choosing an appropriate projection and using GEOMETRY is the best solution, in terms of performance and functionality available.</para></listitem>
		<listitem><para>If your data is global or covers a continental region, you may find that GEOGRAPHY allows you to build a system without having to worry about projection details.
				You store your data in longitude/latitude, and use the functions that have been defined on GEOGRAPHY.</para></listitem>
		<listitem><para>If you don't understand projections, and you don't want to learn about them, and you're prepared to accept the limitations in functionality available in GEOGRAPHY, then it might be easier for you to use GEOGRAPHY than GEOMETRY.
		Simply load your data up as longitude/latitude and go from there.</para></listitem>
	</itemizedlist>
	<para>Refer to <xref linkend="PostGIS_TypeFunctionMatrix" /> for compare between
			what is supported for Geography vs. Geometry.  For a brief listing and description of Geography functions, refer to
				<xref linkend="PostGIS_GeographyFunctions" />
		</para>
	</sect3>
	<sect3 id="PostGIS_Geography_AdvancedFAQ">
			<title>Geography Advanced FAQ</title>
			<qandaset>
				<qandaentry>
				  <question>
					<para>Do you calculate on the sphere or the spheroid?</para>
				  </question>

				  <answer>
					<para> By default, all distance and area calculations are done on the spheroid. You should find that the results of calculations in local areas match up will with local planar results in good local projections.
					Over larger areas, the spheroidal calculations will be more accurate than any calculation done on a projected plane.
					</para>
					<para>All the geography functions have the option of using a sphere calculation, by setting a final boolean parameter to 'FALSE'. This will somewhat speed up calculations, particularly for cases where the geometries are very simple.</para>
				  </answer>
				</qandaentry>

				<qandaentry>
				  <question>
					<para>What about the date-line and the poles?</para>
				  </question>

				  <answer>
					<para> All the calculations have no conception of date-line or poles, the coordinates are spherical (longitude/latitude)
					so a shape that crosses the dateline is, from a calculation point of view, no different from any other shape.
					</para>
				  </answer>
				</qandaentry>

				<qandaentry>
				  <question>
					<para>What is the longest arc you can process?</para>
				  </question>

				  <answer>
					<para>We use great circle arcs as the "interpolation line" between two points. That means any two points are actually joined up two ways, depending on which direction you travel along the great circle. All our code assumes that the points are joined by the *shorter* of the two paths along the great circle.
					As a consequence, shapes that have arcs of more than 180 degrees will not be correctly modelled.</para>
				  </answer>
				</qandaentry>

				<qandaentry>
				  <question>
					<para>Why is it so slow to calculate the area of Europe / Russia / insert big geographic region here ?</para>
				  </question>

				  <answer>
					<para>Because the polygon is so darned huge! Big areas are bad for two reasons: their bounds are huge,
						so the index tends to pull the feature no matter what query you run; the number of vertices is huge,
						and tests (distance, containment) have to traverse the vertex list at least once and sometimes N times
						(with N being the number of vertices in the other candidate feature).
					</para>
					<para>As with GEOMETRY, we recommend that when you have very large polygons, but are doing queries in small areas, you "denormalize" your geometric data into smaller chunks so that the index can effectively subquery parts of the object and so queries don't have to pull out the whole object every time. Please consult <xref linkend="ST_Subdivide" /> function documentation.
					Just because you *can* store all of Europe in one polygon doesn't mean you *should*.</para>
				  </answer>
				</qandaentry>
			</qandaset>
	</sect3>
</sect2>

  <sect2>
	<title>Spatial Metadata Tables</title>

	<para>The OpenGIS "Simple Features Specification for SQL" defines some
	metadata tables to describe geometry table structure and coordinate systems.
    In order to ensure that metadata remains consistent,
	operations such as creating and removing a spatial column are carried out
	through special procedures defined by OpenGIS.</para>

	<para>There are two OpenGIS meta-data tables:
	<varname>SPATIAL_REF_SYS</varname> and
	<varname>GEOMETRY_COLUMNS</varname>. The
	<varname>SPATIAL_REF_SYS</varname> table holds the numeric IDs and textual
	descriptions of coordinate systems used in the spatial database.</para>

	<sect3 id="spatial_ref_sys">
	  <title>The SPATIAL_REF_SYS Table and Spatial Reference Systems</title>

	<para>The <varname>SPATIAL_REF_SYS</varname> table used by PostGIS
    is an OGC-compliant database table that lists over 3000
	known <ulink url="https://en.wikipedia.org/wiki/Spatial_reference_system">spatial reference systems</ulink>
	and details needed to transform (reproject) between them.</para>

    <para>The PostGIS <varname>SPATIAL_REF_SYS</varname> table contains over 3000 of
    the most common spatial reference system definitions that are handled by the
    <ulink url="https://proj.org">PROJ</ulink> projection library.
    But there are many coordinate systems that it does not contain.
    You can define your own custom spatial reference system if you are familiar with PROJ constructs.
    Keep in mind that most spatial reference systems are regional
    and have no meaning when used outside of the bounds they were intended for.</para>

    <para>A resource for finding spatial reference systems not defined in the core set is <ulink url="http://spatialreference.org/">http://spatialreference.org/</ulink></para>

	  <para>Some commonly used spatial reference systems are:
            <ulink url="http://spatialreference.org/ref/epsg/4326/">4326 - WGS 84 Long Lat</ulink>,
			<ulink url="http://spatialreference.org/ref/epsg/4269/">4269 - NAD 83 Long Lat</ulink>,
			<ulink url="http://spatialreference.org/ref/epsg/3395/">3395 - WGS 84 World Mercator</ulink>,
			<ulink url="http://spatialreference.org/ref/epsg/2163/">2163 - US National Atlas Equal Area</ulink>,
        and the 60 WGS84 UTM zones.
		UTM zones are one of the most ideal for measurement, but only cover 6-degree regions.
        (To determine which UTM zone to use for your area of interest, see the <ulink url="http://trac.osgeo.org/postgis/wiki/UsersWikiplpgsqlfunctionsDistance">utmzone PostGIS plpgsql helper function</ulink>.)
	</para>
	<para>
		US states use State Plane spatial reference systems (meter or feet based) - usually one or 2 exists per state.
        Most of the meter-based ones are in the core set, but many of the
		feet-based ones or ESRI created ones will need to be copied from <ulink url="http://spatialreference.org">spatialreference.org</ulink>.
	</para>

	<para>You can even define non-Earth-based coordinate systems,
    such as <ulink url="http://spatialreference.org/ref/iau2000/mars-2000/">Mars 2000</ulink>
 This Mars coordinate system is non-planar (it's in degrees spheroidal),
 but you can use it with the <varname>geography</varname> type to obtain length and proximity measurements in meters instead of degrees.</para>

	  <para>The <varname>SPATIAL_REF_SYS</varname> table definition is:</para>

	  <programlisting>CREATE TABLE spatial_ref_sys (
  srid       INTEGER NOT NULL PRIMARY KEY,
  auth_name  VARCHAR(256),
  auth_srid  INTEGER,
  srtext     VARCHAR(2048),
  proj4text  VARCHAR(2048)
)</programlisting>

	  <para>The columns are:</para>

	  <variablelist>
		<varlistentry>
		  <term>SRID</term>

		  <listitem>
			<para>An integer code that uniquely identifies the <ulink url="http://en.wikipedia.org/wiki/SRID">Spatial
			Reference System</ulink> (SRS) within the database.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>AUTH_NAME</term>

		  <listitem>
			<para>The name of the standard or standards body that is being
			cited for this reference system. For example, "EPSG" is a
			valid <varname>AUTH_NAME</varname>.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>AUTH_SRID</term>

		  <listitem>
			<para>The ID of the Spatial Reference System as defined by the
			Authority cited in the <varname>AUTH_NAME</varname>. In the case
			of EPSG, this is where the EPSG projection code would go.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>SRTEXT</term>

		  <listitem>
			<para>The Well-Known Text representation of the Spatial Reference
			System. An example of a WKT SRS representation is:</para>

			<programlisting>PROJCS["NAD83 / UTM Zone 10N",
  GEOGCS["NAD83",
	DATUM["North_American_Datum_1983",
	  SPHEROID["GRS 1980",6378137,298.257222101]
	],
	PRIMEM["Greenwich",0],
	UNIT["degree",0.0174532925199433]
  ],
  PROJECTION["Transverse_Mercator"],
  PARAMETER["latitude_of_origin",0],
  PARAMETER["central_meridian",-123],
  PARAMETER["scale_factor",0.9996],
  PARAMETER["false_easting",500000],
  PARAMETER["false_northing",0],
  UNIT["metre",1]
]</programlisting>

			<para>For a listing of EPSG projection codes and their
			corresponding WKT representations, see <ulink
			url="http://www.opengeospatial.org/">http://www.opengeospatial.org/</ulink>.
			For a discussion of SRS WKT in general, see the OpenGIS "Coordinate
			Transformation Services Implementation Specification" at <ulink
			url="http://www.opengeospatial.org/standards">http://www.opengeospatial.org/standards</ulink>.
			For information on the European Petroleum Survey Group (EPSG) and
			their database of spatial reference systems, see <ulink
			url="http://www.epsg.org/">http://www.epsg.org</ulink>.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>PROJ4TEXT</term>

		  <listitem>
			<para>PostGIS uses the PROJ library to provide coordinate
			transformation capabilities. The <varname>PROJ4TEXT</varname>
			column contains the Proj4 coordinate definition string for a
			particular SRID. For example:</para>

			<programlisting>+proj=utm +zone=10 +ellps=clrk66 +datum=NAD27 +units=m</programlisting>

			<para>For more information see the
            <ulink url="https://proj.org/">Proj4 web site</ulink>.
			The <filename>spatial_ref_sys.sql</filename> file contains both
			<varname>SRTEXT</varname> and <varname>PROJ4TEXT</varname>
			definitions for all EPSG projections.</para>
		  </listitem>
		</varlistentry>
	  </variablelist>
	</sect3>

	<sect3 id="geometry_columns">
	  <title>The GEOMETRY_COLUMNS View</title>

	  <para><varname>GEOMETRY_COLUMNS</varname> is a view reading from database system catalog tables.
	  Its structure is:</para>

	  <programlisting>\d geometry_columns</programlisting>
<screen>             View "public.geometry_columns"
      Column       |          Type          | Modifiers
-------------------+------------------------+-----------
 f_table_catalog   | character varying(256) |
 f_table_schema    | character varying(256) |
 f_table_name      | character varying(256) |
 f_geometry_column | character varying(256) |
 coord_dimension   | integer                |
 srid              | integer                |
 type              | character varying(30)  |</screen>

	  <para>The columns are:</para>

	  <variablelist>
		<varlistentry>
		  <term>F_TABLE_CATALOG, F_TABLE_SCHEMA, F_TABLE_NAME</term>

		  <listitem>
			<para>The fully qualified name of the feature table containing the
			geometry column. Note that the terms "catalog" and "schema" are
			Oracle-ish. There is not PostgreSQL analogue of "catalog" so that
			column is left blank -- for "schema" the PostgreSQL schema name is
			used (<varname>public</varname> is the default).</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>F_GEOMETRY_COLUMN</term>

		  <listitem>
			<para>The name of the geometry column in the feature table.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>COORD_DIMENSION</term>

		  <listitem>
			<para>The spatial dimension (2, 3 or 4 dimensional) of the
			column.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>SRID</term>

		  <listitem>
			<para>The ID of the spatial reference system used for the
			coordinate geometry in this table. It is a foreign key reference
			to the <varname>SPATIAL_REF_SYS</varname>.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>TYPE</term>

		  <listitem>
			<para>The type of the spatial object. To restrict the spatial
			column to a single type, use one of: POINT, LINESTRING, POLYGON,
			MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION or
			corresponding XYM versions POINTM, LINESTRINGM, POLYGONM,
			MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM.
			For heterogeneous (mixed-type) collections, you can use "GEOMETRY"
			as the type.</para>

			<note>
			  <para>This attribute is (probably) not part of the OpenGIS
			  specification, but is required for ensuring type
			  homogeneity.</para>
			</note>
		  </listitem>
		</varlistentry>
	  </variablelist>
	</sect3>

	<sect3 id="Create_Spatial_Table">
	  <title>Creating a Spatial Table</title>

	  <para>Creating a table with spatial data, can be done in one step. As shown in the following example
	  which creates a roads table with a 2D linestring geometry column in WGS84 long lat</para>
	  <programlisting>CREATE TABLE ROADS (ID serial, ROAD_NAME text, geom geometry(LINESTRING,4326) );</programlisting>

	  <para>We can add additional columns using standard ALTER TABLE command as we do in this next example where we add a 3-D linestring.</para>
	  <programlisting>ALTER TABLE roads ADD COLUMN geom2 geometry(LINESTRINGZ,4326);</programlisting>
	</sect3>

	  <sect3 id="Manual_Register_Spatial_Column">
		<title>Manually Registering Geometry Columns</title>

		<para>Two of the cases where you may need this are the case of SQL Views and bulk inserts.  For bulk insert case, you can correct the registration in the geometry_columns table
		by constraining the column or doing an alter table.  For views, you could expose using a CAST operation.
		Note, if your column is typmod based, the creation process would register it correctly, so no need to do anything.
		Also views that have no spatial function applied to the geometry will register the same as the underlying table geometry column.</para>

		<programlisting>-- Lets say you have a view created like this
CREATE VIEW public.vwmytablemercator AS
	SELECT gid, ST_Transform(geom, 3395) As geom, f_name
	FROM public.mytable;

-- For it to register correctly
-- You need to cast the geometry
--
DROP VIEW public.vwmytablemercator;
CREATE VIEW  public.vwmytablemercator AS
	SELECT gid, ST_Transform(geom, 3395)::geometry(Geometry, 3395) As geom, f_name
	FROM public.mytable;

-- If you know the geometry type for sure is a 2D POLYGON then you could do
DROP VIEW public.vwmytablemercator;
CREATE VIEW  public.vwmytablemercator AS
	SELECT gid, ST_Transform(geom,3395)::geometry(Polygon, 3395) As geom, f_name
	FROM public.mytable;</programlisting>
		<programlisting>--Lets say you created a derivative table by doing a bulk insert
SELECT poi.gid, poi.geom, citybounds.city_name
INTO myschema.my_special_pois
FROM poi INNER JOIN citybounds ON ST_Intersects(citybounds.geom, poi.geom);

-- Create 2D index on new table
CREATE INDEX idx_myschema_myspecialpois_geom_gist
  ON myschema.my_special_pois USING gist(geom);

-- If your points are 3D points or 3M points,
-- then you might want to create an nd index instead of a 2D index
CREATE INDEX my_special_pois_geom_gist_nd
	ON my_special_pois USING gist(geom gist_geometry_ops_nd);

-- To manually register this new table's geometry column in geometry_columns.
-- Note it will also change the underlying structure of the table to
-- to make the column typmod based.
SELECT populate_geometry_columns('myschema.my_special_pois'::regclass);

-- If you are using PostGIS 2.0 and for whatever reason, you
-- you need the constraint based definition behavior
-- (such as case of inherited tables where all children do not have the same type and srid)
-- set optional use_typmod argument to false
SELECT populate_geometry_columns('myschema.my_special_pois'::regclass, false); </programlisting>

<para>Although the old-constraint based method is still supported, a constraint-based geometry column used directly
in a view, will not register correctly in geometry_columns, as will a typmod one.
In this example we define a column using typmod and another using constraints.</para>
<programlisting>CREATE TABLE pois_ny(gid SERIAL PRIMARY KEY, poi_name text, cat text, geom geometry(POINT,4326));
SELECT AddGeometryColumn('pois_ny', 'geom_2160', 2160, 'POINT', 2, false);</programlisting>
<para>If we run in psql</para>
<programlisting>\d pois_ny;</programlisting>
<para>We observe they are defined differently -- one is typmod, one is constraint</para>
<screen>                                  Table "public.pois_ny"
  Column   |         Type          |                       Modifiers

-----------+-----------------------+------------------------------------------------------
 gid       | integer               | not null default nextval('pois_ny_gid_seq'::regclass)
 poi_name  | text                  |
 cat       | character varying(20) |
 geom      | geometry(Point,4326)  |
 geom_2160 | geometry              |
Indexes:
    "pois_ny_pkey" PRIMARY KEY, btree (gid)
Check constraints:
    "enforce_dims_geom_2160" CHECK (st_ndims(geom_2160) = 2)
    "enforce_geotype_geom_2160" CHECK (geometrytype(geom_2160) = 'POINT'::text
        OR geom_2160 IS NULL)
    "enforce_srid_geom_2160" CHECK (st_srid(geom_2160) = 2160)</screen>
<para>In geometry_columns, they both register correctly</para>
<programlisting>SELECT f_table_name, f_geometry_column, srid, type
	FROM geometry_columns
	WHERE f_table_name = 'pois_ny';</programlisting>
<screen>f_table_name | f_geometry_column | srid | type
-------------+-------------------+------+-------
pois_ny      | geom              | 4326 | POINT
pois_ny      | geom_2160         | 2160 | POINT</screen>
<para>However -- if we were to create a view like this</para>
<programlisting>CREATE VIEW vw_pois_ny_parks AS
SELECT *
  FROM pois_ny
  WHERE cat='park';

SELECT f_table_name, f_geometry_column, srid, type
	FROM geometry_columns
	WHERE f_table_name = 'vw_pois_ny_parks';</programlisting>
<para>The typmod based geom view column registers correctly,
but the constraint based one does not.</para>
<screen>   f_table_name   | f_geometry_column | srid |   type
------------------+-------------------+------+----------
 vw_pois_ny_parks | geom              | 4326 | POINT
 vw_pois_ny_parks | geom_2160         |    0 | GEOMETRY</screen>

<para>This may change in future versions of PostGIS, but for now
to force the constraint-based view column to register correctly, you need to do this:</para>
<programlisting>DROP VIEW vw_pois_ny_parks;
CREATE VIEW vw_pois_ny_parks AS
SELECT gid, poi_name, cat,
  geom,
  geom_2160::geometry(POINT,2160) As geom_2160
  FROM pois_ny
  WHERE cat = 'park';
SELECT f_table_name, f_geometry_column, srid, type
	FROM geometry_columns
	WHERE f_table_name = 'vw_pois_ny_parks';</programlisting>
<screen>   f_table_name   | f_geometry_column | srid | type
------------------+-------------------+------+-------
 vw_pois_ny_parks | geom              | 4326 | POINT
 vw_pois_ny_parks | geom_2160         | 2160 | POINT</screen>
    </sect3>
</sect2>
<!-- ==============================================================  -->
<sect2 id="OGC_Validity">
	  <title>Geometry Validation</title>

	  <para>PostGIS is compliant with the Open Geospatial Consortium’s (OGC)
	  OpenGIS Specifications.  As such, many PostGIS methods require, or more
	  accurately, assume that geometries that are operated on are both simple
	  and valid. For example, it does not make sense to calculate the area of
	  a polygon that has a hole defined outside of the polygon, or to construct
	  a polygon from a non-simple boundary line.</para>

	  <para>According to the OGC Specifications, a <emphasis>simple</emphasis>
	  geometry is one that has no anomalous geometric points, such as self
	  intersection or self tangency and primarily refers to 0 or 1-dimensional
	  geometries (i.e. <varname>[MULTI]POINT, [MULTI]LINESTRING</varname>).
	  Geometry validity, on the other hand, primarily refers to 2-dimensional
	  geometries (i.e. <varname>[MULTI]POLYGON)</varname> and defines the set
	  of assertions that characterizes a valid polygon. The description of each
	  geometric class includes specific conditions that further detail geometric
	  simplicity and validity.</para>

	  <para>A <varname>POINT</varname> is inherently <emphasis>simple</emphasis>
	  as a 0-dimensional geometry object.</para>

	  <para><varname>MULTIPOINT</varname>s are <emphasis>simple</emphasis> if
	  no two coordinates (<varname>POINT</varname>s) are equal (have identical
	  coordinate values).</para>

	  <para>A <varname>LINESTRING</varname> is <emphasis>simple</emphasis> if
	  it does not pass through the same <varname>POINT</varname> twice (except
	  for the endpoints, in which case it is referred to as a linear ring and
	  additionally considered closed).</para>

	  <informaltable border="0" frame="none">
		<tgroup cols="2" align="center">
		  <tbody>
			<row>
			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_issimple01.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(a)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_issimple02.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(b)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>
			</row>

			<row>
			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_issimple03.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(c)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_issimple04.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(d)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>
			</row>
		  </tbody>
		</tgroup>

		<tgroup cols="1">
		  <tbody>
			<row>
				<entry><para><emphasis role="bold">(a)</emphasis> and
				<emphasis role="bold">(c)</emphasis> are simple
				<varname>LINESTRING</varname>s, <emphasis role="bold">(b)</emphasis>
				and <emphasis role="bold">(d)</emphasis> are not.</para></entry>
			</row>
		  </tbody>
		</tgroup>
	  </informaltable>

	  <para>A <varname>MULTILINESTRING</varname> is <emphasis>simple</emphasis>
	  only if all of its elements are simple and the only intersection between
	  any two elements occurs at <varname>POINT</varname>s that are on the
	  boundaries of both elements.  </para>

	  <informaltable border="0" frame="none">
		<tgroup cols="3" align="center">
		  <tbody>
			<row>
			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_issimple05.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(e)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_issimple06.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(f)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_issimple07.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(g)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>
			</row>
		  </tbody>
		</tgroup>

		<tgroup cols="1">
		  <tbody>
			<row>
				<entry><para><emphasis role="bold">(e)</emphasis> and
				<emphasis role="bold">(f)</emphasis> are simple
				<varname>MULTILINESTRING</varname>s, <emphasis role="bold">(g)</emphasis>
				is not.</para></entry>
			</row>
		  </tbody>
		</tgroup>
	  </informaltable>

	  <para>By definition, a <varname>POLYGON</varname> is always
	  <emphasis>simple</emphasis>. It is <emphasis>valid</emphasis> if no two
	  rings in the boundary (made up of an exterior ring and interior rings)
	  cross.  The boundary of a <varname>POLYGON</varname> may intersect at a
	  <varname>POINT</varname> but only as a tangent (i.e. not on a line).
	  A <varname>POLYGON</varname> may not have cut lines or spikes and the
	  interior rings must be contained entirely within the exterior ring.</para>

	  <informaltable border="0" frame="none">
		<tgroup cols="3" align="center">
		  <tbody>
			<row>
			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid01.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(h)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid02.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(i)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid03.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(j)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>
			</row>
			<row>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid04.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(k)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid05.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(l)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid06.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(m)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>
			</row>
		  </tbody>
		</tgroup>
		<tgroup cols="1">
		  <tbody>
			<row>
				<entry><para><emphasis role="bold">(h)</emphasis> and
				<emphasis role="bold">(i)</emphasis> are valid
				<varname>POLYGON</varname>s, <emphasis role="bold">(j-m)</emphasis>
				cannot be represented as single <varname>POLYGON</varname>s, but
				<emphasis role="bold">(j)</emphasis> and <emphasis role="bold">(m)</emphasis>
				could be represented as a valid <varname>MULTIPOLYGON</varname>.
				</para></entry>
			</row>
		  </tbody>
		</tgroup>
	  </informaltable>

	  <para>A <varname>MULTIPOLYGON</varname> is <emphasis>valid</emphasis>
	  if and only if all of its elements are valid and the interiors of no two
	  elements intersect. The boundaries of any two elements may touch, but
	  only at a finite number of <varname>POINT</varname>s.</para>

	  <informaltable border="0" frame="none">
		<tgroup cols="2" align="center">
		  <tbody>
			<row>
			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid07.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(n)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid08.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(o)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>

			  <entry><para><informalfigure>
				  <mediaobject>
					<imageobject>
					  <imagedata fileref="images/st_isvalid09.png" />
					</imageobject>

					<caption><para><emphasis role="bold">(p)</emphasis></para></caption>
				  </mediaobject>
				</informalfigure></para></entry>
			</row>
		  </tbody>
		</tgroup>
		<tgroup cols="1">
		  <tbody>
			<row>
				<entry><para><emphasis role="bold">(n)</emphasis> and
				<emphasis role="bold">(o)</emphasis> are not valid
				<varname>MULTIPOLYGON</varname>s.
				<emphasis role="bold">(p)</emphasis>, however, is valid.</para></entry>
			</row>
		  </tbody>
		</tgroup>
	  </informaltable>

	  <para>Most of the functions implemented by the GEOS library rely on the
	  assumption that your geometries are valid as specified by the OpenGIS
	  Simple Feature Specification. To check simplicity or validity of
	  geometries you can use the <link linkend="ST_IsSimple">ST_IsSimple()</link> and
	  <link linkend="ST_IsValid">ST_IsValid()</link></para>

	  <programlisting>-- Typically, it doesn't make sense to check
-- for validity on linear features since it will always return TRUE.
-- But in this example, PostGIS extends the definition of the OGC IsValid
-- by returning false if a LineString has less than 2 *distinct* vertices.
gisdb=# SELECT
   ST_IsValid('LINESTRING(0 0, 1 1)'),
   ST_IsValid('LINESTRING(0 0, 0 0, 0 0)');

 st_isvalid | st_isvalid
------------+-----------
      t     |     f</programlisting>

	  <para>By default, PostGIS does not apply this validity check on geometry
	  input, because testing for validity needs lots of CPU time for complex
	  geometries, especially polygons. If you do not trust your data sources,
	  you can manually enforce such a check to your tables by adding a check
	  constraint:</para>

	  <programlisting>ALTER TABLE mytable
  ADD CONSTRAINT geometry_valid_check
	CHECK (ST_IsValid(the_geom));</programlisting>

	  <para>If you encounter any strange error messages such as "GEOS
	  Intersection() threw an error!" when calling PostGIS functions with valid
		input geometries, you likely found an error in either PostGIS or one of
		the libraries it uses, and you should contact the PostGIS developers.
		The same is true if a PostGIS function returns an invalid geometry for
		valid input.</para>

	  <note>
		<para>Strictly compliant OGC geometries cannot have Z or M values. The
		<link linkend="ST_IsValid">ST_IsValid()</link> function won't consider
		higher dimensioned geometries invalid! Invocations of <link
		linkend="AddGeometryColumn">AddGeometryColumn()</link> will add a
		constraint checking geometry dimensions, so it is enough to specify 2
		there.</para>
	  </note>
</sect2>

  <sect2 id="loading-data">
	<title>Loading Spatial Data</title>

	<para>Once you have created a spatial table, you are ready to upload spatial
	data to the database. There are two built-in ways to get spatial data into a
	PostGIS/PostgreSQL database: using formatted SQL statements or using the
	Shapefile loader.</para>

	<sect3>
	  <title>Using SQL to Load Data</title>

	  <para>If spatial data can be converted to a text representation (as either WKT or WKB), then using
	  SQL might be the easiest way to get data into PostGIS.
      Data can be bulk-loaded into PostGIS/PostgreSQL by loading a
	  text file of SQL <code>INSERT</code> statements using the <code>psql</code> SQL utility.</para>

	  <para>A SQL load file (<filename>roads.sql</filename> for example)
	  might look like this:</para>

	  <programlisting>BEGIN;
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (1,'LINESTRING(191232 243118,191108 243242)','Jeff Rd');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (2,'LINESTRING(189141 244158,189265 244817)','Geordie Rd');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (3,'LINESTRING(192783 228138,192612 229814)','Paul St');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (4,'LINESTRING(189412 252431,189631 259122)','Graeme Ave');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (5,'LINESTRING(190131 224148,190871 228134)','Phil Tce');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (6,'LINESTRING(198231 263418,198213 268322)','Dave Cres');
COMMIT;</programlisting>

	  <para>The SQL file can be loaded into PostgreSQL using <code>psql</code>:</para>

	  <programlisting>psql -d [database] -f roads.sql</programlisting>
	</sect3>

<sect3 id="shp2pgsql_usage">
  <title>Using the Shapefile Loader</title>

  <para>
    The <filename>shp2pgsql</filename> data loader converts Shapefiles into SQL suitable for
    insertion into a PostGIS/PostgreSQL database either in geometry or geography format.
    The loader has several operating modes selected by command line flags.
  </para>
  <para>There is also a <filename>shp2pgsql-gui</filename> graphical interface with most
	of the options as the command-line loader.
    This may be easier to use for one-off non-scripted loading or if you are new to PostGIS.
	It can also be configured as a plugin to PgAdminIII.
	</para>

  <variablelist>
    <varlistentry>
      <term>(c|a|d|p) These are mutually exclusive options:</term>
      <listitem>
        <para>
          <variablelist>
            <varlistentry>
              <term>-c</term>
              <listitem>
                <para>
                  Creates a new table and populates it from the Shapefile. <emphasis>This is the
                  default mode.</emphasis>
                </para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>-a</term>
              <listitem>
                <para>
                  Appends data from the Shapefile into the database table. Note that to use this
                  option to load multiple files, the files must have the same attributes and same
                  data types.
                </para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>-d</term>
              <listitem>
                <para>
                  Drops the database table before creating a new table with the data in the Shapefile.
                </para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>-p</term>
              <listitem>
                <para>
                  Only produces the table creation SQL code, without adding any actual data. This
                  can be used if you need to completely separate the table creation and data loading
                  steps.
                </para>
              </listitem>
            </varlistentry>
          </variablelist>
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-?</term>
      <listitem>
        <para>
          Display help screen.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-D</term>
      <listitem>
        <para>
          Use the PostgreSQL "dump" format for the output data. This can be combined with -a, -c and
          -d. It is much faster to load than the default "insert" SQL format. Use this for very
          large data sets.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-s [&lt;FROM_SRID&gt;:]&lt;SRID&gt;</term>
      <listitem>
        <para>
          Creates and populates the geometry tables with the specified SRID.
          Optionally specifies that the input shapefile uses the given
          FROM_SRID, in which case the geometries will be reprojected to the
          target SRID.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-k</term>
      <listitem>
        <para>
          Keep identifiers' case (column, schema and attributes). Note that attributes in Shapefile
          are all UPPERCASE.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-i</term>
      <listitem>
        <para>
          Coerce all integers to standard 32-bit integers, do not create 64-bit bigints, even if the
          DBF header signature appears to warrant it.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-I</term>
      <listitem>
        <para>
          Create a GiST index on the geometry column.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-m</term>
      <listitem>
        <para>
          -m <filename>a_file_name</filename>  Specify a file containing a set of mappings of (long) column
     names to 10 character DBF column names. The content of the file is one or
     more lines of two names separated by white space and no trailing or
     leading space. For example:
         <programlisting>COLUMNNAME DBFFIELD1
AVERYLONGCOLUMNNAME DBFFIELD2</programlisting>
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-S </term>
      <listitem>
        <para>
          Generate simple geometries instead of MULTI geometries.  Will only succeed if
          all the geometries are actually single (I.E. a MULTIPOLYGON with a single shell, or
          or a MULTIPOINT with a single vertex).
        </para>
      </listitem>
    </varlistentry>

     <varlistentry>
      <term>-t &lt;dimensionality&gt;</term>
      <listitem>
        <para>
          Force the output geometry to have the specified dimensionality. Use the following
          strings to indicate the dimensionality: 2D, 3DZ, 3DM, 4D.
        </para>
        <para>
	        If the input has fewer dimensions that specified, the output will have those dimensions filled
	        in with zeroes. If the input has more dimensions that specified, the unwanted dimensions will
	        be stripped.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-w</term>
      <listitem>
        <para>
          Output WKT format, instead of WKB.  Note that this can
          introduce coordinate drifts due to loss of precision.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-e</term>
      <listitem>
        <para>
          Execute each statement on its own, without using a transaction.
          This allows loading of the majority of good data when there are some bad
          geometries that generate errors.  Note that this cannot be used with the
          -D flag as the "dump" format always uses a transaction.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-W &lt;encoding&gt;</term>
      <listitem>
        <para>
          Specify encoding of the input data (dbf file). When used, all attributes of the dbf are
          converted from the specified encoding to UTF8. The resulting SQL output will contain a
          <code>SET CLIENT_ENCODING to UTF8</code> command, so that the backend will be able to
          reconvert from UTF8 to whatever encoding the database is configured to use internally.
        </para>
      </listitem>
    </varlistentry>

    <varlistentry>
      <term>-N &lt;policy&gt;</term>
      <listitem>
        <para>
           NULL geometries handling policy (insert*,skip,abort)
        </para>
      </listitem>
    </varlistentry>
    <varlistentry>
      <term>-n</term>
      <listitem>
        <para>
          -n  Only import DBF file.  If your data has no corresponding shapefile, it will automatically switch to this mode
	and load just the dbf.  So setting this flag is only needed if you have a full shapefile set, and you only want the attribute data and no geometry.
        </para>
      </listitem>
    </varlistentry>

	<varlistentry>
	  <term>-G</term>
	  <listitem>
		<para>
			Use geography type instead of geometry (requires lon/lat data) in WGS84 long lat (SRID=4326)
		</para>
	  </listitem>
	</varlistentry>
    <varlistentry>
      <term>-T &lt;tablespace&gt;</term>
      <listitem>
        <para>
          Specify the tablespace for the new table.  Indexes will still use the
          default tablespace unless the -X parameter is also used.  The PostgreSQL
          documentation has a good description on when to use custom tablespaces.
        </para>
      </listitem>
    </varlistentry>
    <varlistentry>
      <term>-X &lt;tablespace&gt;</term>
      <listitem>
        <para>
          Specify the tablespace for the new table's indexes.  This applies to
          the primary key index, and the GIST spatial index if -I is also used.
        </para>
      </listitem>
    </varlistentry>
  </variablelist>

  <para>
    An example session using the loader to create an input file and loading it might look like
    this:
  </para>

  <programlisting># shp2pgsql -c -D -s 4269 -i -I shaperoads.shp myschema.roadstable &gt; roads.sql
# psql -d roadsdb -f roads.sql</programlisting>

  <para>
    A conversion and load can be done in one step using UNIX pipes:
  </para>

  <programlisting># shp2pgsql shaperoads.shp myschema.roadstable | psql -d roadsdb</programlisting>
</sect3>
  </sect2>

  <sect2 id="extracting-data">
	<title>Extracting Spatial Data</title>

	<para>Spatial data can be extracted from the database using either SQL or the
	Shapefile dumper. The section on SQL presents some of
	the functions available to do comparisons and queries on spatial tables.
    </para>

	<sect3>
	  <title>Using SQL to Extract Data</title>

	  <para>The most straightforward way of extracting spatial data out of the
        database is to use a SQL <code>SELECT</code> query
        to define the data set to be extracted
        and dump the resulting columns into a parsable text file:</para>

	  <programlisting>db=# SELECT road_id, ST_AsText(road_geom) AS geom, road_name FROM roads;

road_id | geom                                    | road_name
--------+-----------------------------------------+-----------
	  1 | LINESTRING(191232 243118,191108 243242) | Jeff Rd
	  2 | LINESTRING(189141 244158,189265 244817) | Geordie Rd
	  3 | LINESTRING(192783 228138,192612 229814) | Paul St
	  4 | LINESTRING(189412 252431,189631 259122) | Graeme Ave
	  5 | LINESTRING(190131 224148,190871 228134) | Phil Tce
	  6 | LINESTRING(198231 263418,198213 268322) | Dave Cres
	  7 | LINESTRING(218421 284121,224123 241231) | Chris Way
(6 rows)</programlisting>

	  <para>There will be times when some kind of restriction is
	  necessary to cut down the number of records returned. In the case of
	  attribute-based restrictions, use the same SQL syntax as used
	  with a non-spatial table. In the case of spatial restrictions, the
	  following functions are useful:</para>

	  <variablelist>
		<varlistentry>
		  <term>ST_Intersects</term>

		  <listitem>
			<para>This function tells whether two geometries share any space.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>=</term>

		  <listitem>
			<para>This tests whether two geometries are
			geometrically identical. For example, if 'POLYGON((0 0,1 1,1 0,0
			0))' is the same as 'POLYGON((0 0,1 1,1 0,0 0))' (it is).
			</para>
		  </listitem>
		</varlistentry>
	  </variablelist>

	  <para>Next, you can use these operators in queries. Note that when
	  specifying geometries and boxes on the SQL command line, you must
	  explicitly turn the string representations into geometries function.
		The 312 is a fictitious spatial reference system that matches our data.
	  So, for example:</para>

	  <programlisting>SELECT road_id, road_name
  FROM roads
  WHERE roads_geom='SRID=312;LINESTRING(191232 243118,191108 243242)'::geometry;</programlisting>

	  <para>The above query would return the single record from the
	  "ROADS_GEOM" table in which the geometry was equal to that value.</para>

	  <para>To check whether some of the roads passes in the area defined by a polygon:</para>

	  <programlisting>SELECT road_id, road_name
FROM roads
WHERE ST_Intersects(roads_geom, 'SRID=312;POLYGON((...))');</programlisting>



	  <para>The most common spatial query will probably be a "frame-based"
	  query, used by client software, like data browsers and web mappers, to
	  grab a "map frame" worth of data for display. </para>
		<para>When using the "&amp;&amp;" operator, you can specify either a
	  BOX3D as the comparison feature or a GEOMETRY. When you specify a
	  GEOMETRY, however, its bounding box will be used for the
	  comparison.</para>
		<para>Using a "BOX3D" object for the frame, such a query looks like this:</para>

	  <programlisting>SELECT ST_AsText(roads_geom) AS geom
FROM roads
WHERE
  roads_geom &amp;&amp; ST_MakeEnvelope(191232, 243117,191232, 243119,312);</programlisting>

	  <para>Note the use of the SRID 312, to specify the projection of the envelope.</para>


	</sect3>

	<sect3 id="pgsql2shp-usage">
	  <title>Using the Shapefile Dumper</title>

	  <para>The <filename>pgsql2shp</filename> table dumper connects
	  to the database and converts a table (possibly defined by a query) into
	  a shape file. The basic syntax is:</para>

	  <programlisting>pgsql2shp [&lt;options&gt;] &lt;database&gt; [&lt;schema&gt;.]&lt;table&gt;</programlisting>

	  <programlisting>pgsql2shp [&lt;options&gt;] &lt;database&gt; &lt;query&gt;</programlisting>

	  <para>The commandline options are:</para>

	  <variablelist>
		<varlistentry>
		  <term>-f &lt;filename&gt;</term>

		  <listitem>
			<para>Write the output to a particular filename.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>-h &lt;host&gt;</term>

		  <listitem>
			<para>The database host to connect to.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>-p &lt;port&gt;</term>

		  <listitem>
			<para>The port to connect to on the database host.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>-P &lt;password&gt;</term>

		  <listitem>
			<para>The password to use when connecting to the database.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>-u &lt;user&gt;</term>

		  <listitem>
			<para>The username to use when connecting to the database.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>-g &lt;geometry column&gt;</term>

		  <listitem>
			<para>In the case of tables with multiple geometry columns, the
			geometry column to use when writing the shape file.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>-b</term>

		  <listitem>
			<para>Use a binary cursor. This will make the operation faster,
			but will not work if any NON-geometry attribute in the table lacks
			a cast to text.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>-r</term>

		  <listitem>
			<para>Raw mode. Do not drop the <varname>gid</varname> field, or
			escape column names.</para>
		  </listitem>
		</varlistentry>

		<varlistentry>
		  <term>-m <varname>filename</varname></term>
		  <listitem>
			<para> Remap identifiers to ten character names.
			The content of the file is lines of two symbols separated by
			a single white space and no trailing or leading space:
			VERYLONGSYMBOL SHORTONE
			ANOTHERVERYLONGSYMBOL SHORTER
			etc.</para>
		  </listitem>
		</varlistentry>
	  </variablelist>
	</sect3>
  </sect2>

  <sect2 id="build-indexes">
	<title>Building Spatial Indexes</title>

	<para>Indexes make using a spatial database for large data sets
	possible. Without indexing, a search for features would require a
	sequential scan of every record in the database. Indexing speeds up
	searching by organizing the data into a structure which can be quickly
	traversed to find records.
    </para>
    <para>The B-tree index method commonly used for attribute data
    is not very useful for spatial data, since it only supports storing and querying
    data in a single dimension.
    Data such as geometry which has 2 or more dimensions)
    requires an index method that supports range query across all the data dimensions.
    (That said, it is possible to effectively index so-called XY data using a B-tree
    and explict range searches.)
    One of the main advantages of PostgreSQL for spatial data handling is that it offers several kinds of
	indexes which work well for multi-dimensional data: GiST, BRIN and SP-GiST indexes.</para>

	<itemizedlist>
	  <listitem>
		<para><emphasis role="bold">GiST (Generalized Search Tree)</emphasis> indexes break up data into
		"things to one side", "things which overlap", "things which are
		inside" and can be used on a wide range of data-types, including GIS
		data. PostGIS uses an R-Tree index implemented on top of GiST to index
		spatial data. GiST is the most commonly-used and versatile spatial index method,
        and offers very good query performance.
        </para>
	  </listitem>

	  <listitem>
		<para><emphasis role="bold">BRIN (Block Range Index)</emphasis> indexes operate by summarizing
        the spatial extent of ranges of table records.
        Search is done via a scan of the ranges.
        BRIN is only appropriate for use for some kinds of data
        (spatially sorted, with infrequent or no update).
        But it provides much faster index create time, and much smaller index size.
        </para>
	  </listitem>

	  <listitem>
		<para><emphasis role="bold">SP-GiST (Space-Partitioned Generalized Search Tree)</emphasis>
        is a generic index method that supports partitioned search trees
        such as quad-trees, k-d trees, and radix trees (tries).
        </para>
	  </listitem>
	</itemizedlist>

    <para>For more information see the
    <ulink url="https://postgis.net/workshops/postgis-intro/indexing.html">PostGIS Workshop</ulink>,
    and the <ulink url="https://www.postgresql.org/docs/current/indexes.html">PostgreSQL documentation</ulink>.
    </para>

	<sect3 id="gist_indexes">
	  <title>GiST Indexes</title>

	  <para>GiST stands for "Generalized Search Tree" and is a generic form of
	  indexing. In addition to GIS indexing, GiST is used to speed up searches
	  on all kinds of irregular data structures (integer arrays, spectral
	  data, etc) which are not amenable to normal B-Tree indexing.</para>

	  <para>Once a GIS data table exceeds a few thousand rows, you will want
	  to build an index to speed up spatial searches of the data (unless all
	  your searches are based on attributes, in which case you'll want to
	  build a normal index on the attribute fields).</para>

	  <para>The syntax for building a GiST index on a "geometry" column is as
	  follows:</para>


	  <para><programlisting>CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] ); </programlisting></para>

	  <para>The above syntax will always build a 2D-index.  To get the an n-dimensional index for the geometry type, you can create one using this syntax:</para>
	  <programlisting>CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);</programlisting>

	  <para>Building a spatial index is a computationally intensive exercise. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:</para>
		<para><programlisting>CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING GIST ( [geometryfield] ); </programlisting></para>

		<para>After building an index, it is sometimes helpful to force PostgreSQL to collect
		table statistics, which are used to optimize query plans:</para>

	  <para><programlisting>VACUUM ANALYZE [table_name] [(column_name)];</programlisting></para>

	</sect3>

	<sect3 id="brin_indexes">
	<title>BRIN Indexes</title>

    <para>BRIN stands for "Block Range Index". It is an general-purpose
    <ulink url="https://www.postgresql.org/docs/current/brin.html">index method</ulink> introduced in PostgreSQL 9.5.
    BRIN is a <emphasis>lossy</emphasis>
    index method, meaning that a a secondary check is required to confirm
    that a record matches a given search condition
    (which is the case for all provided spatial indexes).
    It provides much faster index creation and much smaller index size,
    with reasonable read performance.
    Its primary purpose is to support indexing very large tables
    on columns which have a correlation with their
    physical location within the table. In addition to spatial indexing,
    BRIN can speed up searches on various kinds of attribute data
    structures (integer, arrays etc).</para>

    <para>Once a spatial table exceeds a few thousand rows, you will want
    to build an index to speed up spatial searches of the data.
    GiST indexes are very performant as long as their size doesn't exceed the amount of RAM
    available for the database, and as long as you can afford the index storage
    size, and the cost of index update on write. Otherwise, for very large tables BRIN index can be
    considered as an alternative.</para>

    <para>A BRIN index stores the bounding box enclosing
    all the geometries contained in the rows in a contiguous set of table blocks,
    called a <emphasis>block range</emphasis>.
    When executing a query using the index the block ranges are scanned to
    find the ones that intersect the query extent.
    This is efficient only if the data is physically ordered so that the bounding
    boxes for block ranges have minimal overlap (and ideally are mutually exclusive).
    The resulting index is very small in size,
    but is typically less performant for read than a GiST index over the same data.</para>

    <para>Building a BRIN index is much less CPU-intensive than building a GiST index.
    It's common to find that a BRIN index is ten times faster to build
    than a GiST index over the same data. And because a BRIN index stores only one
    bounding box for each range of table blocks, it's common to use
    up to a thousand times less disk space than a GiST index.</para>

    <para>You can choose the number of blocks to summarize in a range. If you
    decrease this number, the index will be bigger but will probably provide
    better performance.</para>

    <para>For BRIN to be effective, the table data should be stored in
    a physical order which minimizes the amount of block extent overlap.
    It may be that the data is already sorted appropriately
    (for instance, if it is loaded from another dataset that is already sorted in spatial order).
    Otherwise, this can be accomplished by sorting the data by a one-dimensional spatial key.
    One way to do this is to create a new table sorted by the geometry values
    (which in recent PostGIS versions uses an efficient Hilbert curve ordering):
    </para>

    <para><programlisting>
CREATE TABLE table_sorted AS
   SELECT * FROM table  ORDER BY geom;
</programlisting></para>

    <para>Alternatively, data can be sorted in-place by using a GeoHash as a (temporary) index,
    and clustering on that index:
    </para>

    <para><programlisting>
CREATE INDEX idx_temp_geohash ON table
    USING btree (ST_GeoHash( ST_Transform( geom, 4326 ), 20));
CLUSTER table USING idx_temp_geohash;
</programlisting></para>


    <para>The syntax for building a BRIN index on a <code>geometry</code> column is:</para>

    <para><programlisting>CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geome_col] ); </programlisting></para>

    <para>The above syntax builds a 2D index.  To build a 3D-dimensional index, use this syntax:</para>

    <programlisting>
CREATE INDEX [indexname] ON [tablename]
    USING BRIN ([geome_col] brin_geometry_inclusion_ops_3d);</programlisting>

    <para>You can also get a 4D-dimensional index using the 4D operator class:</para>

    <programlisting>
CREATE INDEX [indexname] ON [tablename]
    USING BRIN ([geome_col] brin_geometry_inclusion_ops_4d);</programlisting>

    <para>The above commands use the default number of blocks in a range, which is 128.
    To specify the number of blocks to summarise in a range, use this syntax</para>

    <para><programlisting>
CREATE INDEX [indexname] ON [tablename]
    USING BRIN ( [geome_col] ) WITH (pages_per_range = [number]); </programlisting></para>

    <para>Keep in mind that a BRIN index only stores one index
    entry for a large number of rows.  If your table stores geometries with
    a mixed number of dimensions, it's likely that the resulting index will
    have poor performance.  You can avoid this performance penalty by
    choosing the operator class with the least number of dimensions of the
    stored geometries
    </para>

    <para>The <code>geography</code> datatype is supported for BRIN indexing. The
    syntax for building a BRIN index on a geography column is:</para>

    <para><programlisting>CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geog_col] ); </programlisting></para>

    <para>The above syntax builds a 2D-index for geospatial objects on the spheroid. </para>

    <para>Currently, only "inclusion support" is provided, meaning
    that just the <varname>&amp;&amp;</varname>, <varname>~</varname> and
    <varname>@</varname> operators can be used for the 2D cases (for both
    <code>geometry</code> and <code>geography</code>), and just the <varname>&amp;&amp;&amp;</varname>
    operator for 3D geometries.
    There is currently no support for kNN searches.</para>

    <para>An important difference between BRIN and other index types is that the database does not
    maintain the index dynamically.  Changes to spatial data in the table
    are simply appended to the end of the index.  This will cause index search performance to
    degrade over time.  The index can be updated by performing a <code>VACUUM</code>,
    or by using a special function <code>brin_summarize_new_values(regclass)</code>.
    For this reason BRIN may be most appropriate for use with data that is read-only,
    or only rarely changing. For more information refer to the
    <ulink url="https://www.postgresql.org/docs/current/brin-intro.html#BRIN-OPERATION">manual</ulink>.
    </para>

    <para>To summarize using BRIN for spatial data:
    </para>

    <itemizedlist>
    <listitem><para>Index build time is very fast, and index size is very small.</para></listitem>
    <listitem><para>Index query time is slower than GiST, but can still be very acceptable.</para></listitem>
    <listitem><para>Requires table data to be sorted in a spatial ordering.</para></listitem>
    <listitem><para>Requires manual index maintenance.</para></listitem>
    <listitem><para>Most appropriate for very large tables,
    with low or no overlap (e.g. points),
    and which are static or change infrequently.</para></listitem>
   </itemizedlist>

	</sect3>

	<sect3 id="spgist_indexes">
	 	<title>SP-GiST Indexes</title>

		<para>SP-GiST stands for "Space-Partitioned Generalized Search Tree" and is
		a generic form of indexing that supports partitioned search trees, such as
		quad-trees, k-d trees, and radix trees (tries). The common feature of these
		data structures is that they repeatedly divide the search space into
		partitions that need not be of equal size. In addition to GIS indexing,
		SP-GiST is used to speed up searches on many kinds of data, such as phone
		routing, ip routing, substring search, etc. </para>

    <para>As it is the case for GiST indexes, SP-GiST indexes are lossy, in the
		sense that they store the bounding box enclosing spatial objects.
		SP-GiST indexes can be considered as an alternative to GiST indexes. The
		performance tests reveal that SP-GiST indexes are especially beneficial
		when there are many overlapping objects, that is, with so-called
		“spaghetti data”.</para>

		<para>Once a GIS data table exceeds a few thousand rows, an SP-GiST index
		may be used to speed up spatial searches of the data. The syntax for
		building an SP-GiST index on a "geometry" column is as follows:</para>

		<para><programlisting>CREATE INDEX [indexname] ON [tablename] USING SPGIST ( [geometryfield] ); </programlisting></para>

		<para>The above syntax will build a 2-dimensional index. A 3-dimensional
		index for the geometry type can be created using the 3D operator class:</para>

		<para><programlisting>CREATE INDEX [indexname] ON [tablename] USING SPGIST ([geometryfield] spgist_geometry_ops_3d);</programlisting></para>

		<para>Building a spatial index is a computationally intensive operation.
		It also blocks write access to your table for the time it creates, so on a
		production system you may want to do in in a slower CONCURRENTLY-aware way:</para>

	  <para><programlisting>CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING SPGIST ( [geometryfield] ); </programlisting></para>

		<para>After building an index, it is sometimes helpful to force PostgreSQL to
		collect table statistics, which are used to optimize query plans:</para>

		<para><programlisting>VACUUM ANALYZE [table_name] [(column_name)];</programlisting></para>

		<para>An SP-GiST index can accelerate queries involving the following operators:</para>
		<itemizedlist>
			<listitem><para>&lt;&lt;, &amp;&lt;, &amp;&gt;, &gt;&gt;, &lt;&lt;|, &amp;&lt;|, |&amp;&gt;, |&gt;&gt;, &amp;&amp;, @&gt;, &lt;@, and ~=, for 2-dimensional indexes,</para></listitem>
			<listitem><para> &amp;/&amp;, ~==, @&gt;&gt;, and &lt;&lt;@, for 3-dimensional indexes.</para></listitem>
		</itemizedlist>
		<para>There is no support for kNN searches at the moment.</para>
	</sect3>
	<sect3>
	  <title>Using Indexes</title>

	  <para>Ordinarily, indexes invisibly speed up data access: once the index
	  is built, the PostgreSQL query planner automatically decides when to use index
	  information to speed up a query plan. Unfortunately, the
	  query planner sometimes does not optimize the use of GiST indexes,
      so queries end up using slow sequential scans instead of a spatial index.</para>

	  <para>If you find your spatial indexes are not being used,
      there are a couple things you can do:</para>

	  <itemizedlist>
		<listitem>
		  <para>Examine the query plan and check your query actually computes the
			thing you need. An erroneous JOIN, either forgotten or to the wrong table,
			can unexpectedly retrieve table records multiple times.
            To get the query plan, execute with <code>EXPLAIN</code> in front of the query.</para>
		</listitem>

		<listitem>
		  <para>Make sure statistics are gathered about the number
		  and distributions of values in a table, to provide the query planner
		  with better information to make decisions around index usage.
			<command>VACUUM ANALYZE</command> will compute both.</para>

			<para>You should regularly vacuum your databases anyways - many PostgreSQL DBAs have
			<command>VACUUM</command> run as an off-peak cron job on a regular basis.</para>
		</listitem>

		<listitem>
		  <para>If vacuuming does not help, you can temporarily force the planner to use
		  the index information by using the <command>set enable_seqscan to off;</command>
			command. This way you can check whether planner is at all capable to generate
			an index accelerated query plan for your query.
			You should only use this command only for debug: generally
		  speaking, the planner knows better than you do about when to use
		  indexes. Once you have run your query, do not forget to set
			<varname>ENABLE_SEQSCAN</varname> back on, so that other queries will utilize
			the planner as normal.</para>
		</listitem>

		<listitem>
		  <para>If <command>set enable_seqscan to off;</command> helps your query to run,
			your Postgres is likely not tuned for your hardware.
			If you find the planner wrong about the cost of sequential vs
		  index scans try reducing the value of <varname>random_page_cost</varname> in
		  postgresql.conf or using <command>set random_page_cost to 1.1;</command>. Default value for
		  the parameter is 4, try setting it to 1 (on SSD) or 2 (on fast magnetic disks).
			Decreasing the value makes the planner more inclined of using Index scans.</para>
		</listitem>

		<listitem>
		  <para>If <command>set enable_seqscan to off;</command> does not help your query,
			the query may be using a SQL construct that the Postgres planner is not yet able to optimize.
            It may be possible to rewrite the query in a way that the planner is able to handle.
			For example, a subquery with an inline SELECT may not produce an efficient plan,
            but could possibly be rewritten using a LATERAL JOIN.</para>
		</listitem>

	  </itemizedlist>
	</sect3>
  </sect2>

</sect1>
