1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
|
<!-- Converted by db4-upgrade version 1.1 -->
<chapter xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="using_postgis_dbmanagement">
<title>Data Management</title>
<section xml:id="RefObject">
<title>Spatial Data Model</title>
<section xml:id="OGC_Geometry">
<title>OGC Geometry</title>
<para>The Open Geospatial Consortium (OGC) developed the
<link xlink:href="https://www.ogc.org/standards/sfa"><emphasis>Simple Features Access</emphasis></link>
standard (SFA) to provide a model for geospatial data.
It defines the fundamental spatial type of <emphasis role="bold">Geometry</emphasis>,
along with operations which manipulate and transform geometry values
to perform spatial analysis tasks.
PostGIS implements the OGC Geometry model as the PostgreSQL data types
<link linkend="PostGIS_Geometry">geometry</link> and
<link linkend="PostGIS_Geography">geography</link>.
</para>
<para>
Geometry is an <emphasis>abstract</emphasis> type.
Geometry values belong to one of its <emphasis>concrete</emphasis> subtypes
which represent various kinds and dimensions of geometric shapes.
These include the <emphasis role="bold">atomic</emphasis> types
<link linkend="Point">Point</link>,
<link linkend="LineString">LineString</link>,
<link linkend="LinearRing">LinearRing</link> and
<link linkend="Polygon">Polygon</link>,
and the <emphasis role="bold">collection</emphasis> types
<link linkend="MultiPoint">MultiPoint</link>,
<link linkend="MultiLineString">MultiLineString</link>,
<link linkend="MultiPolygon">MultiPolygon</link> and
<link linkend="GeometryCollection">GeometryCollection</link>.
The <link xlink:href="https://portal.ogc.org/files/?artifact_id=25355"><emphasis>Simple Features Access - Part 1: Common architecture v1.2.1</emphasis></link>
adds subtypes for the structures
<link linkend="PolyhedralSurface">PolyhedralSurface</link>,
<link linkend="Triangle">Triangle</link> and
<link linkend="TIN">TIN</link>.
</para>
<para>Geometry models shapes in the 2-dimensional Cartesian plane.
The PolyhedralSurface, Triangle, and TIN types can also represent shapes in 3-dimensional space.
The size and location of shapes are specified by their <emphasis role="bold">coordinates</emphasis>.
Each coordinate has a X and Y <emphasis role="bold">ordinate</emphasis> value determining its location in the plane.
Shapes are constructed from points or line segments, with points specified by a single coordinate,
and line segments by two coordinates.
</para>
<para>Coordinates may contain optional Z and M ordinate values.
The Z ordinate is often used to represent elevation.
The M ordinate contains a measure value, which may represent time or distance.
If Z or M values are present in a geometry value, they must be defined for each point in the geometry.
If a geometry has Z or M ordinates the <emphasis role="bold">coordinate dimension</emphasis> is 3D;
if it has both Z and M the coordinate dimension is 4D.
</para>
<para>Geometry values are associated with a
<emphasis role="bold">spatial reference system</emphasis>
indicating the coordinate system in which it is embedded.
The spatial reference system is identified by the geometry SRID number.
The units of the X and Y axes are determined by the spatial reference system.
In <emphasis role="bold">planar</emphasis> reference systems the X and Y coordinates typically
represent easting and northing,
while in <emphasis role="bold">geodetic</emphasis> systems
they represent longitude and latitude.
SRID 0 represents an infinite Cartesian plane with no units assigned to its axes.
See <xref linkend="spatial_ref_sys"/>.
</para>
<para>The geometry <emphasis role="bold">dimension</emphasis> is a property of geometry types.
Point types have dimension 0, linear types have dimension 1,
and polygonal types have dimension 2.
Collections have the dimension of the maximum element dimension.
</para>
<para>A geometry value may be <emphasis role="bold">empty</emphasis>.
Empty values contain no vertices (for atomic geometry types)
or no elements (for collections).
</para>
<para>An important property of geometry values is their spatial
<emphasis role="bold">extent</emphasis> or <emphasis role="bold">bounding box</emphasis>,
which the OGC model calls <emphasis role="bold">envelope</emphasis>.
This is the 2 or 3-dimensional box which encloses the coordinates of a geometry.
It is an efficient way to represent a geometry's
extent in coordinate space and to check whether two geometries interact.
</para>
<para>The geometry model allows evaluating topological spatial relationships as
described in <xref linkend="DE-9IM"/>.
To support this the concepts of
<emphasis role="bold">interior</emphasis>,
<emphasis role="bold">boundary</emphasis> and
<emphasis role="bold">exterior</emphasis>
are defined for each geometry type.
Geometries are topologically closed, so they always contain their boundary.
The boundary is a geometry of dimension one less than that of the geometry itself.
</para>
<para>The OGC geometry model defines validity rules for each geometry type.
These rules ensure that geometry values represents realistic
situations (e.g. it is possible to specify a polygon
with a hole lying outside the shell, but this makes no sense geometrically
and is thus invalid).
PostGIS also allows storing and manipulating invalid geometry values.
This allows detecting and fixing them if needed.
See <xref linkend="OGC_Validity"/>
</para>
<section xml:id="Point">
<title>Point</title>
<para>A Point is a 0-dimensional geometry that represents a single location in coordinate space.</para>
<programlisting>POINT (1 2)
POINT Z (1 2 3)
POINT ZM (1 2 3 4)
</programlisting>
</section>
<section xml:id="LineString">
<title>LineString</title>
<para>A LineString is a 1-dimensional line formed by a contiguous sequence of line segments.
Each line segment is defined by two points, with the end point of one segment
forming the start point of the next segment.
An OGC-valid LineString has either zero or two or more points,
but PostGIS also allows single-point LineStrings.
LineStrings may cross themselves (self-intersect).
A LineString is <emphasis role="bold">closed</emphasis> if the start and end points are the same.
A LineString is <emphasis role="bold">simple</emphasis> if it does not self-intersect.
</para>
<programlisting>LINESTRING (1 2, 3 4, 5 6)</programlisting>
</section>
<section xml:id="LinearRing">
<title>LinearRing</title>
<para>A LinearRing is a LineString which is both closed and simple.
The first and last points must be equal, and the line must not self-intersect.</para>
<programlisting>LINEARRING (0 0 0, 4 0 0, 4 4 0, 0 4 0, 0 0 0)</programlisting>
</section>
<section xml:id="Polygon">
<title>Polygon</title>
<para>A Polygon is a 2-dimensional planar region,
delimited by an exterior boundary (the shell)
and zero or more interior boundaries (holes).
Each boundary is a <link linkend="LinearRing">LinearRing</link>.
</para>
<programlisting>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))</programlisting>
</section>
<section xml:id="MultiPoint">
<title>MultiPoint</title>
<para>A MultiPoint is a collection of Points.</para>
<programlisting>MULTIPOINT ( (0 0), (1 2) )</programlisting>
</section>
<section xml:id="MultiLineString">
<title>MultiLineString</title>
<para>A MultiLineString is a collection of LineStrings.
A MultiLineString is closed if each of its elements is closed.
</para>
<programlisting>MULTILINESTRING ( (0 0,1 1,1 2), (2 3,3 2,5 4) )</programlisting>
</section>
<section xml:id="MultiPolygon">
<title>MultiPolygon</title>
<para>A MultiPolygon is a collection of non-overlapping, non-adjacent Polygons.
Polygons in the collection may touch only at a finite number of points.
</para>
<programlisting>MULTIPOLYGON (((1 5, 5 5, 5 1, 1 1, 1 5)), ((6 5, 9 1, 6 1, 6 5)))</programlisting>
</section>
<section xml:id="GeometryCollection">
<title>GeometryCollection</title>
<para>A GeometryCollection is a heterogeneous (mixed) collection of geometries.</para>
<programlisting>GEOMETRYCOLLECTION ( POINT(2 3), LINESTRING(2 3, 3 4))</programlisting>
</section>
<section xml:id="PolyhedralSurface">
<title>PolyhedralSurface</title>
<para>A PolyhedralSurface is a contiguous collection of patches or facets which share some edges.
Each patch is a planar Polygon.
If the Polygon coordinates have Z ordinates then the surface is 3-dimensional.</para>
<programlisting>POLYHEDRALSURFACE Z (
((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)) )</programlisting>
</section>
<section xml:id="Triangle">
<title>Triangle</title>
<para>A Triangle is a polygon defined by three distinct non-collinear vertices.
Because a Triangle is a polygon it is specified by four coordinates,
with the first and fourth being equal.
</para>
<programlisting>TRIANGLE ((0 0, 0 9, 9 0, 0 0))</programlisting>
</section>
<section xml:id="TIN">
<title>TIN</title>
<para>A TIN is a collection of non-overlapping
<link linkend="Triangle">Triangle</link>s representing a
<link xlink:href="https://en.wikipedia.org/wiki/Triangulated_irregular_network">Triangulated Irregular Network</link>.
</para>
<programlisting>TIN Z ( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )</programlisting>
</section>
</section>
<section xml:id="SQL_MM_Part3">
<title>SQL/MM Part 3 - Curves</title>
<para>The
<link xlink:href="https://www.iso.org/obp/ui/#iso:std:iso-iec:13249:-3:ed-5:v1:en"><emphasis>ISO/IEC 13249-3 SQL Multimedia - Spatial</emphasis></link>
standard (SQL/MM) extends the
OGC SFA to define Geometry subtypes containing curves with circular arcs.
The SQL/MM types support 3DM, 3DZ and 4D coordinates.
</para>
<note>
<para>All floating point comparisons within the SQL-MM implementation
are performed to a specified tolerance, currently 1E-8.</para>
</note>
<section xml:id="CircularString">
<title>CircularString</title>
<para>CircularString is the basic curve type, similar to a
LineString in the linear world. A single arc segment is specified by three
points: the start and end points (first and third) and some other
point on the arc.
To specify a closed circle the start and end points are the same
and the middle point is the opposite point on the circle diameter
(which is the center of the arc).
In a sequence of arcs the end point of the previous
arc is the start point of the next arc, just like the segments of a LineString.
This means that a CircularString must have an
odd number of points greater than 1.</para>
<programlisting>CIRCULARSTRING(0 0, 1 1, 1 0)
CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)</programlisting>
</section>
<section xml:id="CompoundCurve">
<title>CompoundCurve</title>
<para>A CompoundCurve is a single continuous curve that may contain both
circular arc 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>
<programlisting>COMPOUNDCURVE( CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))</programlisting>
</section>
<section xml:id="CurvePolygon">
<title>CurvePolygon</title>
<para>A CurvePolygon is like a polygon, with an outer ring
and zero or more inner rings. The difference is that a ring can be a
CircularString or CompoundCurve as well as a LineString.
</para>
<para>As of PostGIS 1.4 PostGIS supports compound curves in a curve polygon.</para>
<programlisting>CURVEPOLYGON(
CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),
(1 1, 3 3, 3 1, 1 1) )</programlisting>
<para>Example: A CurvePolygon with the shell defined by a CompoundCurve
containing a CircularString and a LineString,
and a hole defined by a CircularString</para>
<programlisting>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) )</programlisting>
</section>
<section xml:id="MultiCurve">
<title>MultiCurve</title>
<para>A MultiCurve is a collection of curves which can include
LineStrings, CircularStrings or CompoundCurves.</para>
<programlisting>MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4))</programlisting>
</section>
<section xml:id="MultiSurface">
<title>MultiSurface</title>
<para>A MultiSurface is a collection of surfaces, which can be (linear)
Polygons or CurvePolygons.</para>
<programlisting>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)))</programlisting>
</section>
</section>
<section xml:id="OpenGISWKBWKT">
<title>WKT and WKB</title>
<para>The OGC SFA specification defines two formats for representing
geometry values for external use: Well-Known Text (WKT) and Well-Known
Binary (WKB). Both WKT and WKB include information about the type
of the object and the coordinates which define it.</para>
<para>Well-Known Text (WKT) provides a standard textual representation of spatial data.
Examples of WKT representations of spatial objects are:</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>POINT EMPTY</para>
</listitem>
<listitem>
<para>LINESTRING(0 0,1 1,1 2)</para>
</listitem>
<listitem>
<para>LINESTRING EMPTY</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>MULTIPOINT EMPTY</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>
<listitem>
<para>GEOMETRYCOLLECTION EMPTY</para>
</listitem>
</itemizedlist>
<para>Input and output of WKT is provided by the functions
<xref linkend="ST_AsText"/> and <xref linkend="ST_GeomFromText"/>:</para>
<programlisting>text WKT = ST_AsText(geometry);
geometry = ST_GeomFromText(text WKT, SRID);</programlisting>
<para>For example, a statement to create and insert a spatial object from WKT and a SRID is:</para>
<programlisting>INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'A Place');</programlisting>
<para>Well-Known Binary (WKB) provides a portable, full-precision representation
of spatial data as binary data (arrays of bytes).
Examples of the WKB representations of spatial objects are:</para>
<itemizedlist>
<listitem>
<para>WKT: POINT(1 1)</para>
<para>WKB: 0101000000000000000000F03F000000000000F03</para>
</listitem>
<listitem>
<para>WKT: LINESTRING (2 2, 9 9)</para>
<para>WKB: 0102000000020000000000000000000040000000000000004000000000000022400000000000002240</para>
</listitem>
</itemizedlist>
<para>Input and output of WKB is provided by the functions
<xref linkend="ST_AsBinary"/> and <xref linkend="ST_GeomFromWKB"/>:</para>
<programlisting>
bytea WKB = ST_AsBinary(geometry);
geometry = ST_GeomFromWKB(bytea WKB, SRID);
</programlisting>
<para>For example, a statement to create and insert a
spatial object from WKB is:</para>
<programlisting>INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromWKB('\x0101000000000000000000f03f000000000000f03f', 312), 'A Place');</programlisting>
</section>
</section>
<section xml:id="PostGIS_Geometry">
<title>Geometry Data Type</title>
<para>PostGIS implements the OGC Simple Features model
by defining a PostgreSQL data type called <varname>geometry</varname>.
It represents all of the geometry subtypes by using an internal type code
(see <xref linkend="GeometryType"/> and <xref linkend="ST_GeometryType"/>).
This allows modelling spatial features as rows of tables defined
with a column of type <varname>geometry</varname>.
</para>
<para>The <varname>geometry</varname> data type is <emphasis>opaque</emphasis>,
which means that all access is done via invoking functions on geometry values.
Functions allow creating geometry objects,
accessing or updating all internal fields,
and compute new geometry values.
PostGIS supports all the functions specified in the OGC
<link xlink:href="https://portal.ogc.org/files/?artifact_id=25354"><emphasis>Simple feature access - Part 2: SQL option</emphasis></link>
(SFS) specification, as well many others.
See <xref linkend="reference"/> for the full list of functions.</para>
<note>
<para>PostGIS follows the SFA standard by prefixing spatial functions with "ST_".
This was intended to stand for "Spatial and Temporal",
but the temporal part of the standard was never developed.
Instead it can be interpreted as "Spatial Type".
</para>
</note>
<para>The SFA standard specifies that spatial objects include a Spatial Reference System
identifier (SRID). The SRID is required when creating spatial objects
for insertion into the database (it may be defaulted to 0).
See <xref linkend="ST_SRID"/> and <xref linkend="spatial_ref_sys"/></para>
<para>To make querying geometry efficient PostGIS defines
various kinds of spatial indexes, and spatial operators to use them.
See <xref linkend="build-indexes"/> and <xref linkend="using-query-indexes"/> for details.
</para>
<section xml:id="EWKB_EWKT">
<title>PostGIS EWKB and EWKT</title>
<para>OGC SFA specifications initially supported only 2D geometries,
and the geometry SRID is not included in the input/output representations.
The OGC SFA specification 1.2.1 (which aligns with the ISO 19125 standard)
adds support for 3D (ZYZ) and measured (XYM and XYZM) coordinates,
but still does not include the SRID value.</para>
<para>Because of these limitations PostGIS defined extended EWKB and EWKT formats.
They provide 3D (XYZ and XYM) and 4D (XYZM) coordinate support and include SRID information.
Including all geometry information allows PostGIS to use EWKB as the format of record
(e.g. in DUMP files).
</para>
<para>EWKB and EWKT are used for the "canonical forms" of PostGIS data objects.
For input, the canonical form for binary data is EWKB,
and for text data either EWKB or EWKT is accepted.
This allows geometry values to be created by casting
a text value in either HEXEWKB or EWKT to a geometry value using <varname>::geometry</varname>.
For output, the canonical form for binary is EWKB, and for text
it is HEXEWKB (hex-encoded EWKB).
</para>
<para>For example this statement creates a geometry by casting from an EWKT text value,
and outputs it using the canonical form of HEXEWKB:</para>
<programlisting>SELECT 'SRID=4;POINT(0 0)'::geometry;
geometry
----------------------------------------------------
01010000200400000000000000000000000000000000000000
</programlisting>
<para>PostGIS EWKT output has a few differences to OGC WKT:</para>
<itemizedlist>
<listitem>
<para>For 3DZ geometries the Z qualifier is omitted:</para>
<para>OGC: POINT Z (1 2 3)</para>
<para>EWKT: POINT (1 2 3)</para>
</listitem>
<listitem>
<para>For 3DM geometries the M qualifier is included:</para>
<para>OGC: POINT M (1 2 3)</para>
<para>EWKT: POINTM (1 2 3)</para>
</listitem>
<listitem>
<para>For 4D geometries the ZM qualifier is omitted:</para>
<para>OGC: POINT ZM (1 2 3 4)</para>
<para>EWKT: POINT (1 2 3 4)</para>
</listitem>
</itemizedlist>
<para>EWKT avoids over-specifying dimensionality
and the inconsistencies that can occur with the OGC/ISO format, such as:
</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 a superset of the OGC ones,
so that every valid OGC WKB/WKT is also valid EWKB/EWKT.
However, this might vary in the future,
if the OGC extends a format in a way that conflicts with the PosGIS definition.
Thus you SHOULD NOT rely on this compatibility!</para>
</caution>
<para>Examples of the EWKT text representation of spatial objects are:</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 10, 10 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>Input and output using these formats is available using the following functions:</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 statement to create and insert a PostGIS spatial object using EWKT is:</para>
<programlisting>INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )</programlisting>
</section>
</section>
<section xml:id="PostGIS_Geography">
<title>Geography Data Type</title>
<para>The PostGIS <varname>geography</varname> data 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 data type is a plane.
The shortest path between two points on the plane is a straight line.
That means functions on geometries (areas, distances, lengths, intersections, etc)
are calculated using straight line vectors and cartesian mathematics.
This makes them simpler to implement and faster to execute,
but also makes them inaccurate for data on the spheroidal surface of the earth.
</para>
<para>The PostGIS geography data type is based on a spherical model.
The shortest path between two points on the sphere is a great circle arc.
Functions on geographies (areas, distances, lengths, intersections, etc) are calculated using arcs on the sphere.
By taking the spheroidal shape of the world into account, the functions provide more accurate results.</para>
<para>Because the underlying mathematics is 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.
As a workaround one can convert back and forth between geometry and geography types.</para>
<para>Like the geometry data type, geography data is associated
with a spatial reference system via a spatial reference system identifier (SRID).
Any geodetic (long/lat based) spatial reference system defined in the <varname>spatial_ref_sys</varname> table can be used.
(Prior to PostGIS 2.2, the geography type supported only WGS 84 geodetic (SRID:4326)).
You can add your own custom geodetic spatial reference system as described in <xref linkend="user-spatial-ref-sys"/>.</para>
<para>For all spatial reference systems the units returned by measurement functions
(e.g. <xref linkend="ST_Distance"/>, <xref linkend="ST_Length"/>, <xref linkend="ST_Perimeter"/>, <xref linkend="ST_Area"/>)
and for the distance argument of <xref linkend="ST_DWithin"/> are in meters.</para>
<section xml:id="Create_Geography_Tables">
<title>Creating Geography Tables</title>
<para>You can create a table to store geography data using the
<link xlink:href="https://www.postgresql.org/docs/current/sql-createtable.html">CREATE TABLE</link>
SQL statement with a column of type <varname>geography</varname>.
The following example creates a table with a geography column storing 2D LineStrings
in the WGS84 geodetic coordinate system (SRID 4326):</para>
<programlisting>CREATE TABLE global_points (
id SERIAL PRIMARY KEY,
name VARCHAR(64),
location geography(POINT,4326)
);</programlisting>
<para>The geography type supports two optional type modifiers:</para>
<itemizedlist>
<listitem>
<para>the spatial type modifier restricts the kind of shapes and dimensions allowed in the column.
Values allowed for the spatial type are: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION.
The geography type does not support curves, TINS, or POLYHEDRALSURFACEs.
The modifier supports coordinate dimensionality restrictions by adding suffixes: Z, M and ZM.
For example, a modifier of 'LINESTRINGM' only allows linestrings with three dimensions, and treats the third dimension as a measure.
Similarly, 'POINTZM' requires four dimensional (XYZM) data.
</para>
</listitem>
<listitem>
<para>the SRID modifier restricts the spatial reference system SRID to a particular number.
If omitted, the SRID defaults to 4326 (WGS84 geodetic), and all calculations are performed using WGS84.
</para>
</listitem>
</itemizedlist>
<para/>
<para>Examples of creating tables with geography columns:</para>
<itemizedlist>
<listitem>
<para>Create a table with 2D POINT geography with the default SRID 4326 (WGS84 long/lat):</para>
<para><programlisting>CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT) );</programlisting></para>
</listitem>
<listitem>
<para>Create 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>
</listitem>
<listitem>
<para>Create a table with 3D (XYZ) POINTs and an explicit SRID of 4326:</para>
<para><programlisting>CREATE TABLE ptzgeogwgs84(gid serial PRIMARY KEY, geog geography(POINTZ,4326) );</programlisting></para>
</listitem>
<listitem>
<para>Create a table with 2D LINESTRING geography with the default SRID 4326:</para>
<para><programlisting>CREATE TABLE lgeog(gid serial PRIMARY KEY, geog geography(LINESTRING) );</programlisting></para>
</listitem>
<listitem>
<para>Create a table with 2D POLYGON geography with the SRID 4267 (NAD 1927 long lat):</para>
<para><programlisting>CREATE TABLE lgeognad27(gid serial PRIMARY KEY, geog geography(POLYGON,4267) );</programlisting></para>
</listitem>
<!-- TODO: Add other examples -->
<!--
<listitem>
<para>MULTIPOINT</para>
</listitem>
<listitem>
<para>MULTILINESTRING</para>
</listitem>
<listitem>
<para>MULTIPOLYGON</para>
</listitem>
<listitem>
<para>GEOMETRYCOLLECTION</para>
</listitem>
-->
</itemizedlist>
<para>Geography fields are registered in the <varname>geography_columns</varname> system view.
You can query the <varname>geography_columns</varname> view and see that the table is listed:</para>
<programlisting>
SELECT * FROM geography_columns;</programlisting>
<para>Creating a spatial index works the same as for geometry columns.
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>
<programlisting>-- Index the test table with a spherical index
CREATE INDEX global_points_gix ON global_points USING GIST ( location );</programlisting>
</section>
<section xml:id="Use_Geography_Tables">
<title>Using Geography Tables</title>
<para>You can insert data into geography tables in the same way as geometry.
Geometry data will autocast to the geography type if it has SRID 4326.
The <link linkend="EWKB_EWKT">EWKT and EWKB</link> formats can also be used
to specify geography values.</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>Any geodetic (long/lat) spatial reference system listed in
<varname>spatial_ref_sys</varname> table may be specified as a geography SRID.
Non-geodetic coordinate systems raise an error if used.
</para>
<programlisting>-- NAD 83 lon/lat
SELECT 'SRID=4269;POINT(-123 34)'::geography;
geography
----------------------------------------------------
0101000020AD1000000000000000C05EC00000000000004140
</programlisting>
<programlisting>-- NAD27 lon/lat
SELECT 'SRID=4267;POINT(-123 34)'::geography;
geography
----------------------------------------------------
0101000020AB1000000000000000C05EC00000000000004140
</programlisting>
<programlisting>-- NAD83 UTM zone meters - gives an error since it is a meter-based planar projection
SELECT 'SRID=26910;POINT(-123 34)'::geography;
ERROR: Only lon/lat coordinate systems are supported in geography.
</programlisting>
<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>
<programlisting>-- A distance query using a 1000km tolerance
SELECT name FROM global_points WHERE ST_DWithin(location, 'SRID=4326;POINT(-110 29)'::geography, 1000000);</programlisting>
<para>You can see the power of geography in action by calculating how close a plane flying
a great circle route from Seattle to London (LINESTRING(-122.33 47.606, 0.0 51.5))
comes to Reykjavik (POINT(-21.96 64.15))
(<link xlink:href="http://gc.kls2.com/cgi-bin/gc?PATH=SEA-LHR">map the route</link>).
</para>
<para>The geography type calculates the true shortest distance of 122.235 km over the sphere
between Reykjavik and the great circle flight path between Seattle and London.</para>
<programlisting>-- Distance calculation using GEOGRAPHY
SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)'::geography);
st_distance
-----------------
122235.23815667</programlisting>
<para>
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 is "degrees",
but the result doesn't correspond to any true angular difference between the points,
so even calling them "degrees" is inaccurate.</para>
<programlisting>-- Distance calculation using GEOMETRY
SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15)'::geometry);
st_distance
--------------------
13.342271221453624
</programlisting>
</section>
<section xml:id="PostGIS_GeographyVSGeometry">
<title>When to use the Geography data type</title>
<para>The geography data 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 data type you choose should be determined by 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>
</section>
<section xml: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>
</section>
</section>
<!-- ============================================================== -->
<section xml:id="OGC_Validity">
<title>Geometry Validation</title>
<para>PostGIS is compliant with the Open Geospatial Consortium’s (OGC)
Simple Features specification.
That standard defines the concepts of geometry being
<emphasis>simple</emphasis> and <emphasis>valid</emphasis>.
These definitions allow the Simple Features geometry model
to represent spatial objects in a consistent and unambiguous way
that supports efficient computation.
(Note: the OGC SF and SQL/MM have the same definitions for simple and valid.)
</para>
<section xml:id="Simple_Geometry">
<title>Simple Geometry</title>
<para>A <emphasis>simple</emphasis>
geometry is one that has no anomalous geometric points, such as self
intersection or self tangency.
</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 point twice, except for the endpoints.
If the endpoints of a simple LineString are identical it is called <emphasis>closed</emphasis>
and referred to as a Linear Ring.</para>
<informaltable frame="none">
<tgroup cols="1">
<tbody>
<row>
<entry><para><emphasis>
<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 simple.
<emphasis role="bold">(c)</emphasis> is a closed Linear Ring.
</emphasis></para></entry>
</row>
</tbody>
</tgroup>
<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>
</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 points that are on the
boundaries of both elements. </para>
<informaltable frame="none">
<tgroup cols="1">
<tbody>
<row>
<entry><para><emphasis>
<emphasis role="bold">(e)</emphasis> and
<emphasis role="bold">(f)</emphasis> are simple
<varname>MULTILINESTRING</varname>s.
<emphasis role="bold">(g)</emphasis> is not simple.
</emphasis></para></entry>
</row>
</tbody>
</tgroup>
<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>
</informaltable>
<para><varname>POLYGON</varname>s are formed from linear rings, so
valid polygonal geometry is always <emphasis>simple</emphasis>.</para>
<para>To test if a geometry is simple
use the <xref linkend="ST_IsSimple"/> function:</para>
<programlisting>
SELECT
ST_IsSimple('LINESTRING(0 0, 100 100)') AS straight,
ST_IsSimple('LINESTRING(0 0, 100 100, 100 0, 0 100)') AS crossing;
straight | crossing
----------+----------
t | f
</programlisting>
<para>Generally, PostGIS functions do not require geometric arguments to be simple.
Simplicity is primarily used as a basis for defining geometric validity.
It is also a requirement for some kinds of spatial data models
(for example, linear networks often disallow lines that cross).
Multipoint and linear geometry can be made simple using <xref linkend="ST_UnaryUnion"/>.
</para>
</section>
<section xml:id="Valid_Geometry">
<title>Valid Geometry</title>
<para>Geometry validity primarily applies to 2-dimensional
geometries (<varname>POLYGON</varname>s and <varname>MULTIPOLYGON</varname>s) .
Validity is defined by rules that allow polygonal geometry
to model planar areas unambiguously.
</para>
<para>A <varname>POLYGON</varname> is <emphasis>valid</emphasis> if:
</para>
<orderedlist>
<listitem><para>
the polygon boundary rings (the exterior shell ring and interior hole rings)
are <emphasis>simple</emphasis> (do not cross or self-touch).
Because of this a polygon cannot have cut lines, spikes or loops.
This implies that polygon holes must be represented as interior rings,
rather than by the exterior ring self-touching (a so-called "inverted hole").
</para></listitem>
<listitem><para>
boundary rings do not cross
</para></listitem>
<listitem><para>
boundary rings may touch at points but only as a tangent (i.e. not in a line)
</para></listitem>
<listitem><para>
interior rings are contained in the exterior ring
</para></listitem>
<listitem><para>
the polygon interior is simply connected
(i.e. the rings must not touch in a way that splits the polygon into more than one part)
</para></listitem>
</orderedlist>
<informaltable frame="none">
<tgroup cols="1">
<tbody>
<row>
<entry><para><emphasis>
<emphasis role="bold">(h)</emphasis> and
<emphasis role="bold">(i)</emphasis> are valid <varname>POLYGON</varname>s.
<emphasis role="bold">(j-m)</emphasis> are invalid.
<emphasis role="bold">(j)</emphasis>
can be represented as a valid <varname>MULTIPOLYGON</varname>.
</emphasis></para></entry>
</row>
</tbody>
</tgroup>
<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>
</informaltable>
<para>A <varname>MULTIPOLYGON</varname> is <emphasis>valid</emphasis> if:
</para>
<orderedlist>
<listitem><para>
its element <varname>POLYGON</varname>s are valid
</para></listitem>
<listitem><para>
elements do not overlap (i.e. their interiors must not intersect)
</para></listitem>
<listitem><para>
elements touch only at points (i.e. not along a line)
</para></listitem>
</orderedlist>
<informaltable frame="none">
<tgroup cols="1">
<tbody>
<row>
<entry><para><emphasis>
<emphasis role="bold">(n)</emphasis> is a valid <varname>MULTIPOLYGON</varname>.
<emphasis role="bold">(o)</emphasis> and <emphasis role="bold">(p)</emphasis> are invalid.
</emphasis></para></entry>
</row>
</tbody>
</tgroup>
<tgroup cols="3" align="center">
<tbody>
<row>
<entry><para><informalfigure>
<mediaobject>
<imageobject>
<imagedata fileref="images/st_isvalid09.png"/>
</imageobject>
<caption><para><emphasis role="bold">(n)</emphasis></para></caption>
</mediaobject>
</informalfigure></para></entry>
<entry><para><informalfigure>
<mediaobject>
<imageobject>
<imagedata fileref="images/st_isvalid07.png"/>
</imageobject>
<caption><para><emphasis role="bold">(o)</emphasis></para></caption>
</mediaobject>
</informalfigure></para></entry>
<entry><para><informalfigure>
<mediaobject>
<imageobject>
<imagedata fileref="images/st_isvalid08.png"/>
</imageobject>
<caption><para><emphasis role="bold">(p)</emphasis></para></caption>
</mediaobject>
</informalfigure></para></entry>
</row>
</tbody>
</tgroup>
</informaltable>
<para>These rules mean that valid polygonal geometry is also <emphasis>simple</emphasis>.
</para>
<para>For linear geometry the only validity rule is that <varname>LINESTRING</varname>s must
have at least two points and have non-zero length
(or equivalently, have at least two distinct points.)
Note that non-simple (self-intersecting) lines are valid.
</para>
<programlisting>
SELECT
ST_IsValid('LINESTRING(0 0, 1 1)') AS len_nonzero,
ST_IsValid('LINESTRING(0 0, 0 0, 0 0)') AS len_zero,
ST_IsValid('LINESTRING(10 10, 150 150, 180 50, 20 130)') AS self_int;
len_nonzero | len_zero | self_int
-------------+----------+----------
t | f | t
</programlisting>
<para><varname>POINT</varname> and <varname>MULTIPOINT</varname> geometries
have no validity rules.
</para>
</section>
<section xml:id="Managing_Validity">
<title>Managing Validity</title>
<para>PostGIS allows creating and storing both valid and invalid Geometry.
This allows invalid geometry to be detected and flagged or fixed.
There are also situations where the OGC validity rules are stricter than desired
(examples of this are zero-length linestrings and polygons with inverted holes.)
</para>
<para>Many of the functions provided by PostGIS rely on the
assumption that geometry arguments are 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.
Assuming valid geometric inputs allows functions to operate more efficiently,
since they do not need to check for topological correctness.
(Notable exceptions are that zero-length lines
and polygons with inversions are generally handled correctly.)
Also, most PostGIS functions produce valid geometry output if the inputs are valid.
This allows PostGIS functions to be chained together safely.
</para>
<para>If you encounter unexpected error messages when calling PostGIS functions
(such as "GEOS Intersection() threw an error!"),
you should first confirm that the function arguments are valid.
If they are not, then consider using one of the techniques below to ensure
the data you are processing is valid.
</para>
<note><para>
If a function reports an error with valid inputs,
then you may have found an error in either PostGIS or one of
the libraries it uses, and you should report this to the PostGIS project.
The same is true if a PostGIS function returns an invalid geometry for
valid input.</para></note>
<para>To test if a geometry is valid use the
<xref linkend="ST_IsValid"/> function:
</para>
<programlisting>
SELECT ST_IsValid('POLYGON ((20 180, 180 180, 180 20, 20 20, 20 180))');
-----------------
t
</programlisting>
<para>Information about the nature and location of an geometry invalidity are provided by
the <xref linkend="ST_IsValidDetail"/> function:
</para>
<programlisting>
SELECT valid, reason, ST_AsText(location) AS location
FROM ST_IsValidDetail('POLYGON ((20 20, 120 190, 50 190, 170 50, 20 20))') AS t;
valid | reason | location
-------+-------------------+---------------------------------------------
f | Self-intersection | POINT(91.51162790697674 141.56976744186045)
</programlisting>
<para>In some situations it is desirable to correct invalid geometry automatically.
Use the <xref linkend="ST_MakeValid"/> function to do this.
(<code>ST_MakeValid</code> is a case of a spatial function that <emphasis>does</emphasis> allow invalid input!)
</para>
<para>By default, PostGIS does not check for validity when loading geometry,
because validity testing can take a lot of CPU time for complex
geometries. If you do not trust your data sources,
you can enforce a validity check on your tables by adding a check
constraint:</para>
<programlisting>ALTER TABLE mytable
ADD CONSTRAINT geometry_valid_check
CHECK (ST_IsValid(geom));</programlisting>
</section>
</section>
<!-- ============================================================== -->
<section xml:id="spatial_ref_sys">
<title>Spatial Reference Systems</title>
<para>A <link xlink:href="https://en.wikipedia.org/wiki/Spatial_reference_system">Spatial Reference System</link> (SRS)
(also called a Coordinate Reference System (CRS))
defines how geometry is referenced to locations on the Earth's surface.
There are three types of SRS:
</para>
<itemizedlist>
<listitem><para>A <emphasis role="bold">geodetic</emphasis> SRS uses angular coordinates
(longitude and latitude) which map directly to the surface of the earth.
</para></listitem>
<listitem><para>A <emphasis role="bold">projected</emphasis> SRS
uses a mathematical projection transformation
to "flatten" the surface of the spheroidal earth onto a plane.
It assigns location coordinates in a way that allows direct measurement
of quantities such as distance, area, and angle.
The coordinate system is Cartesian, which means it has a defined origin point
and two perpendicular axes (usually oriented North and East).
Each projected SRS uses a stated length unit (usually metres or feet).
A projected SRS may be limited in its area of applicability to avoid distortion
and fit within the defined coordinate bounds.
</para></listitem>
<listitem><para>A <emphasis role="bold">local</emphasis> SRS
is a Cartesian coordinate system which is not referenced to the earth's surface.
In PostGIS this is specified by a SRID value of 0.
</para></listitem>
</itemizedlist>
<para>
There are many different spatial reference systems in use.
Common SRSes are standardized in the
European Petroleum Survey Group
<link xlink:href="http://www.epsg.org/">EPSG database</link>.
For convenience PostGIS (and many other spatial systems) refers to SRS
definitions using an integer identifier called a SRID.
</para>
<para>A geometry is associated with a Spatial Reference System by its SRID value,
which is accessed by <xref linkend="ST_SRID"/>.
The SRID for a geometry can be assigned using <xref linkend="ST_SetSRID"/>.
Some geometry constructor functions allow supplying a SRID
(such as <xref linkend="ST_Point"/> and <xref linkend="ST_MakeEnvelope"/>).
The <link linkend="EWKB_EWKT">EWKT</link> format supports SRIDs with the <code>SRID=n;</code> prefix.
</para>
<para>
Spatial functions processing pairs of geometries
(such as <link linkend="Overlay_Functions">overlay</link> and
<link linkend="Spatial_Relationships">relationship</link> functions)
require that the input geometries are in the same spatial reference system (have the same SRID).
Geometry data can be transformed into a different spatial reference system using
<xref linkend="ST_Transform"/> and <xref linkend="ST_TransformPipeline"/>.
Geometry returned from functions has the same SRS as the input geometries.
</para>
<section xml:id="spatial_ref_sys_table">
<title>SPATIAL_REF_SYS Table</title>
<para>The <varname>SPATIAL_REF_SYS</varname> table used by PostGIS
is an OGC-compliant database table that defines the available
spatial reference systems.
It holds the numeric SRIDs and textual descriptions of the coordinate systems.
</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><varname>srid</varname></term>
<listitem>
<para>An integer code that uniquely identifies the <link xlink:href="http://en.wikipedia.org/wiki/SRID">Spatial
Reference System</link> (SRS) within the database.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>auth_name</varname></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><varname>auth_srid</varname></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 the EPSG code.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>srtext</varname></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 discussion of SRS WKT, see the OGC standard <link xlink:href="http://docs.opengeospatial.org/is/12-063r5/12-063r5.html">Well-known text representation of coordinate reference systems</link>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>proj4text</varname></term>
<listitem>
<para>PostGIS uses the PROJ library to provide coordinate
transformation capabilities. The <varname>proj4text</varname>
column contains the PROJ 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
<link xlink:href="https://proj.org/">PROJ web site</link>.
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>
<para>When retrieving spatial reference system definitions for use in transformations,
PostGIS uses fhe following strategy:
</para>
<itemizedlist>
<listitem><para>If <varname>auth_name</varname> and <varname>auth_srid</varname>
are present (non-NULL)
use the PROJ SRS based on those entries (if one exists).
</para></listitem>
<listitem><para>If <varname>srtext</varname> is present
create a SRS using it, if possible.
</para></listitem>
<listitem><para>If <varname>proj4text</varname> is present
create a SRS using it, if possible.
</para></listitem>
</itemizedlist>
</section>
<section xml:id="user-spatial-ref-sys">
<title>User-Defined Spatial Reference Systems</title>
<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
<link xlink:href="https://proj.org">PROJ</link> projection library.
But there are many coordinate systems that it does not contain.
You can add SRS definitions to the table if you have
the required information about the spatial reference system.
Or, 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 <link xlink:href="http://spatialreference.org/">http://spatialreference.org/</link></para>
<para>Some commonly used spatial reference systems are:
<link xlink:href="http://spatialreference.org/ref/epsg/4326/">4326 - WGS 84 Long Lat</link>,
<link xlink:href="http://spatialreference.org/ref/epsg/4269/">4269 - NAD 83 Long Lat</link>,
<link xlink:href="http://spatialreference.org/ref/epsg/3395/">3395 - WGS 84 World Mercator</link>,
<link xlink:href="http://spatialreference.org/ref/epsg/2163/">2163 - US National Atlas Equal Area</link>,
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 <link xlink:href="http://trac.osgeo.org/postgis/wiki/UsersWikiplpgsqlfunctionsDistance">utmzone PostGIS plpgsql helper function</link>.)
</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 <link xlink:href="http://spatialreference.org">spatialreference.org</link>.
</para>
<para>You can even define non-Earth-based coordinate systems,
such as <link xlink:href="http://spatialreference.org/ref/iau2000/mars-2000/">Mars 2000</link>
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>Here is an example of loading a custom coordinate system using
an unassigned SRID and the PROJ definition for a US-centric Lambert Conformal projection:</para>
<programlisting>
INSERT INTO spatial_ref_sys (srid, proj4text)
VALUES ( 990000,
'+proj=lcc +lon_0=-95 +lat_0=25 +lat_1=25 +lat_2=25 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'
);
</programlisting>
</section>
</section>
<!-- ============================================================== -->
<section>
<title>Spatial Tables</title>
<section xml:id="Create_Spatial_Table">
<title>Creating a Spatial Table</title>
<para>You can create a table to store geometry data using the
<link xlink:href="https://www.postgresql.org/docs/current/sql-createtable.html">CREATE TABLE</link>
SQL statement with a column of type <varname>geometry</varname>.
The following example creates a table with a geometry column storing 2D (XY) LineStrings
in the BC-Albers coordinate system (SRID 3005):</para>
<programlisting>CREATE TABLE roads (
id SERIAL PRIMARY KEY,
name VARCHAR(64),
geom geometry(LINESTRING,3005)
);</programlisting>
<para>The <varname>geometry</varname> type supports two optional <emphasis role="bold">type modifiers</emphasis>:</para>
<itemizedlist>
<listitem>
<para>the <emphasis role="bold">spatial type modifier</emphasis>
restricts the kind of shapes and dimensions allowed in the column.
The value can be any of the supported
<link linkend="RefObject">geometry subtypes</link>
(e.g. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION, etc).
The modifier supports coordinate dimensionality restrictions by adding suffixes: Z, M and ZM.
For example, a modifier of 'LINESTRINGM' allows only linestrings with three dimensions, and treats the third dimension as a measure.
Similarly, 'POINTZM' requires four dimensional (XYZM) data.
</para>
</listitem>
<listitem>
<para>the <emphasis role="bold">SRID modifier</emphasis> restricts the
<link linkend="spatial_ref_sys">spatial reference system</link> SRID to a particular number.
If omitted, the SRID defaults to 0.
</para>
</listitem>
</itemizedlist>
<para/>
<para>Examples of creating tables with geometry columns:</para>
<itemizedlist>
<listitem>
<para>Create a table holding any kind of geometry with the default SRID:</para>
<para><programlisting>CREATE TABLE geoms(gid serial PRIMARY KEY, geom geometry );</programlisting></para>
</listitem>
<listitem>
<para>Create a table with 2D POINT geometry with the default SRID:</para>
<para><programlisting>CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINT) );</programlisting></para>
</listitem>
<listitem>
<para>Create a table with 3D (XYZ) POINTs and an explicit SRID of 3005:</para>
<para><programlisting>CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINTZ,3005) );</programlisting></para>
</listitem>
<listitem>
<para>Create a table with 4D (XYZM) LINESTRING geometry with the default SRID:</para>
<para><programlisting>CREATE TABLE lines(gid serial PRIMARY KEY, geom geometry(LINESTRINGZM) );</programlisting></para>
</listitem>
<listitem>
<para>Create a table with 2D POLYGON geometry with the SRID 4267 (NAD 1927 long lat):</para>
<para><programlisting>CREATE TABLE polys(gid serial PRIMARY KEY, geom geometry(POLYGON,4267) );</programlisting></para>
</listitem>
</itemizedlist>
<para>It is possible to have more than one geometry column in a table.
This can be specified when the table is created, or a column can be added using the
<link xlink:href="https://www.postgresql.org/docs/current/sql-altertable.html">ALTER TABLE</link>
SQL statement.
This example adds a column that can hold 3D LineStrings:</para>
<programlisting>ALTER TABLE roads ADD COLUMN geom2 geometry(LINESTRINGZ,4326);</programlisting>
</section>
<section xml:id="geometry_columns">
<title>GEOMETRY_COLUMNS View</title>
<para>The OGC <emphasis>Simple Features Specification for SQL</emphasis> defines
the <varname>GEOMETRY_COLUMNS</varname> metadata table to describe geometry table structure.
In PostGIS <varname>geometry_columns</varname> is a view reading from database system catalog tables.
This ensures that the spatial metadata information is always consistent with the currently defined tables and views.
The view 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><varname>f_table_catalog, f_table_schema, f_table_name</varname></term>
<listitem>
<para>The fully qualified name of the feature table containing the
geometry column. There is no 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><varname>f_geometry_column</varname></term>
<listitem>
<para>The name of the geometry column in the feature table.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>coord_dimension</varname></term>
<listitem>
<para>The coordinate dimension (2, 3 or 4) of the column.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>srid</varname></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> table
(see <xref linkend="spatial_ref_sys_table"/>).</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>type</varname></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>
</listitem>
</varlistentry>
</variablelist>
</section>
<section xml: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>
</section>
</section>
<!-- ============================================================== -->
<section xml: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>
<section xml:id="load-data-sql">
<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>
</section>
<section xml: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><option>-c</option></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><option>-a</option></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><option>-d</option></term>
<listitem>
<para>
Drops the database table before creating a new table with the data in the Shapefile.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-p</option></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><option>-?</option></term>
<listitem>
<para>
Display help screen.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-D</option></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><option>-s [<FROM_SRID>:]<SRID></option></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><option>-k</option></term>
<listitem>
<para>
Keep identifiers' case (column, schema and attributes). Note that attributes in Shapefile
are all UPPERCASE.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-i</option></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><option>-I</option></term>
<listitem>
<para>
Create a GiST index on the geometry column.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-m</option></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><option>-S</option></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><option>-t <dimensionality></option></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><option>-w</option></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><option>-e</option></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><option>-W <encoding></option></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><option>-N <policy></option></term>
<listitem>
<para>
NULL geometries handling policy (insert*,skip,abort)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-n</option></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><option>-G</option></term>
<listitem>
<para>
Use geography type instead of geometry (requires lon/lat data) in WGS84 long lat (SRID=4326)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-T <tablespace></option></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><option>-X <tablespace></option></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>
<varlistentry>
<term><option>-Z</option></term>
<listitem>
<para>
When used, this flag will prevent the generation of <code>ANALYZE</code> statements.
Without the -Z flag (default behavior), the <code>ANALYZE</code> statements will
be generated.
</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><![CDATA[
# shp2pgsql -c -D -s 4269 -i -I shaperoads.shp myschema.roadstable > 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>
</section>
</section>
<section xml: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>
<section xml:id="extract-data-sql">
<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><function>ST_Intersects</function></term>
<listitem>
<para>This function tells whether two geometries share any space.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><code>=</code></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 "&&" 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><![CDATA[
SELECT ST_AsText(roads_geom) AS geom
FROM roads
WHERE
roads_geom && ST_MakeEnvelope(191232, 243117,191232, 243119,312);
]]></programlisting>
<para>Note the use of the SRID 312, to specify the projection of the envelope.</para>
</section>
<section xml: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><![CDATA[
pgsql2shp [<options>] <database> [<schema>.]<table>
]]></programlisting>
<programlisting><![CDATA[
pgsql2shp [<options>] <database> <query>
]]></programlisting>
<para>The commandline options are:</para>
<variablelist>
<varlistentry>
<term><option>-f <filename></option></term>
<listitem>
<para>Write the output to a particular filename.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-h <host></option></term>
<listitem>
<para>The database host to connect to.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-p <port></option></term>
<listitem>
<para>The port to connect to on the database host.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-P <password></option></term>
<listitem>
<para>The password to use when connecting to the database.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-u <user></option></term>
<listitem>
<para>The username to use when connecting to the database.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-g <geometry column></option></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><option>-b</option></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><option>-r</option></term>
<listitem>
<para>Raw mode. Do not drop the <varname>gid</varname> field, or
escape column names.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-m filename</option></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>
</section>
</section>
<section xml:id="build-indexes">
<title>Spatial Indexes</title>
<para>Spatial indexes make using a spatial database for large data sets
possible. Without indexing, a search for features requires 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 matching 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.
One of the key advantages of PostgreSQL for spatial data handling is that it offers several kinds of
index methods 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>Spatial indexes store only the bounding box of geometries.
Spatial queries use the index as a <emphasis role="bold">primary filter</emphasis>
to quickly determine a set of geometries potentially matching the query condition.
Most spatial queries require a <emphasis role="bold">secondary filter</emphasis>
that uses a spatial predicate function to test a more specific spatial condition.
For more information on queying with spatial predicates see <xref linkend="using-query-indexes"/>.
</para>
<para>See also the
<link xlink:href="https://postgis.net/workshops/postgis-intro/indexing.html">PostGIS Workshop section on spatial indexes</link>,
and the <link xlink:href="https://www.postgresql.org/docs/current/indexes.html">PostgreSQL manual</link>.
</para>
<section xml:id="gist_indexes">
<title>GiST Indexes</title>
<para>GiST stands for "Generalized Search Tree" and is a generic form of
indexing for multi-dimensional 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.
Other implementations of GiST are 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.
For more information see the <link xlink:href="https://www.postgresql.org/docs/current/gist.html">PostgreSQL manual</link>.
</para>
<para>Once a spatial 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>
</section>
<section xml:id="brin_indexes">
<title>BRIN Indexes</title>
<para>BRIN stands for "Block Range Index". It is a general-purpose
index method introduced in PostgreSQL 9.5.
BRIN is a <emphasis>lossy</emphasis>
index method, meaning that 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).
For more information see the <link xlink:href="https://www.postgresql.org/docs/current/brin.html">PostgreSQL manual</link>.
</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>&&</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>&&&</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
<link xlink:href="https://www.postgresql.org/docs/current/brin-intro.html#BRIN-OPERATION">manual</link>.
</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),
which are static or change infrequently.</para></listitem>
<listitem><para>More effective for queries which return relatively large numbers of data records.</para></listitem>
</itemizedlist>
</section>
<section xml: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 for multi-dimensional data types
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 spatial indexing,
SP-GiST is used to speed up searches on many kinds of data, such as phone
routing, ip routing, substring search, etc.
For more information see the <link xlink:href="https://www.postgresql.org/docs/current/spgist.html">PostgreSQL manual</link>.
</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.</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><<, &<, &>, >>, <<|, &<|, |&>, |>>, &&, @>, <@, and ~=, for 2-dimensional indexes,</para></listitem>
<listitem><para> &/&, ~==, @>>, and <<@, for 3-dimensional indexes.</para></listitem>
</itemizedlist>
<para>There is no support for kNN searches at the moment.</para>
</section>
<section xml:id="tuning-index-usage">
<title>Tuning Index Usage</title>
<para>Ordinarily, indexes invisibly speed up data access: once an index
is built, the PostgreSQL query planner automatically decides when to use it
to improve query performance. But there are some situations
where the planner does not choose to use existing 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 few 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 run
<command>VACUUM</command> 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 <command>SET ENABLE_SEQSCAN TO OFF;</command>.
This way you can check whether the planner is at all able to generate
an index-accelerated query plan for your query.
You should only use this command for debugging; generally
speaking, the planner knows better than you do about when to use
indexes. Once you have run your query, do not forget to run
<command>SET ENABLE_SEQSCAN TO ON;</command> so that the planner
will operate normally for other queries.</para>
</listitem>
<listitem>
<para>If <command>SET ENABLE_SEQSCAN TO OFF;</command> helps your query to run faster,
your Postgres is likely not tuned for your hardware.
If you find the planner wrong about the cost of sequential versus
index scans try reducing the value of <varname>RANDOM_PAGE_COST</varname> in
<code>postgresql.conf</code>, or use <command>SET RANDOM_PAGE_COST TO 1.1;</command>.
The default value for <varname>RANDOM_PAGE_COST</varname> is 4.0.
Try setting it to 1.1 (for SSD) or 2.0 (for fast magnetic disks).
Decreasing the value makes the planner more likely to use 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>
<para>
For more information see the Postgres manual section on
<link xlink:href="https://www.postgresql.org/docs/current/runtime-config-query.html">Query Planning</link>.
</para>
</section>
</section>
</chapter>
|