Intro To PostGIS

  • Upload
    mleslie

  • View
    36.627

  • Download
    14

Embed Size (px)

DESCRIPTION

Slides from my Introduction to PostGIS workshop at the FOSS4G conference in 2009. The material is available at http://revenant.ca/www/postgis/workshop/

Citation preview

  • 1. Introduction to PostGIS Presented by: Mark Leslie Mike Pumphrey Paul Ramsey

2. Workshop Format Interactive C:workshopsintro_to_postgis http://localhost/postgis/workshop Hands On All examples are executable Copy and Paste from HTML Exercises Answers will be provided (eventually) Try Thissections for greater challenge 3. What is a Spatial Database? Spatial Data Types Point a single coordinate of two to four dimensions 4. What is a Spatial Database? Spatial Data Types Linestring a set of two or more coordinates linear interpretation of path between coordinates 5. What is a Spatial Database? Spatial Data Types Linearring a linestring with three or more coordinates the start and end points are the same 6. What is a Spatial Database? Spatial Data Types Polygon a set of one or more linearrings one ring defines the exterior boundary remainder defines the holes in the polygon 7. What is a Spatial Database? Spatial Data Types Multi-geometries (Multipoint, Multilinestring, Multipolygon) a set of like geometries 8. What is a Spatial Database? Spatial Data Types Geometrycollection a set of various (unmatched) geometries 9. What is a Spatial Database? Spatial Data Types Spatial Indexing R-tree Quadtree Grid-based 10. What is a Spatial Database? Spatial Data Types Spatial Indexing Spatial Functions Construction Serialisation Predicates Analysis Accessors Builders Aggregates 11. What is PostGIS? Spatial Extensions for PostgreSQL Provides Spatial Data Type Provides Spatial Indexing Provides Spatial Functions 12. What is PostGIS? Spatial Extensions for PostgreSQL PostgreSQL Extensions for Spatial ACID transaction guarantees Enterprise reliability Crash recovery Hot backup Replication SQL support 13. PostGIS History Initially released May 2001 with only load/store and index support. Functions added based onSimple Features for SQL(SFSQL) UMN MapServer added PostGIS support in mid-2001 Geometry Engine, Open Source (GEOS)was released, providing the hard SFSQL functions PostGIS 1.0 provided a faster, lightweight geometry object 14. Who uses PostGIS? Institut Geographique National, France National mapping agency of France Stores high-res topographic data GlobeXplorer Provides web-based access to petabytes of imagery PostGIS is used to manage metadata and search for relevant imagery 15. PostgreSQL Setup Installing PostgreSQL Software provided it C:workshopsPostGISsoftware Double click postgresql-8.1.1-1-windows.exe Creating a Spatial Database Using pgAdmin III Loading Spatial Data The horrors of the command line 16. PostgreSQL Installation 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. PostGIS Documentation 38. Creating a Spatial Database 39. 40. 41. 42. 43. 44. 45. 46. 47. Loading Data 48. Loading Data Change toC:workshopsPostGISdata Executeset_environment.bat 49. 50. Load the Parks Shapefile shp2pgsql -s 2270 medford_parks.shp medford_parks > medford_parks.sql psql -f medford_parks.sql workshop 51. 52. 53. 54. Load the Schools Shapefile shp2pgsql -s 2270 -D jacksonco_schools.shp jacksonco_schools > jacksonco_schools.sql psql -f jacksonco_schools.sql workshop 55. 56. 57. Load Additional Data psql -f medford.sql workshop 58. 59. Geometries Creating and Manipulating Creating simple geometries Consistent geometries through constraints Geometry types and output Accessing geometry components Measurement Functions 60. Point Creation CREATE TABLE points (name varchar, point geometry) INSERT INTO points VALUES ('Origin', 'POINT(0 0)'), ('North', 'POINT(0 1)'), ('East', 'POINT(1 0)'), ('West', 'POINT(-1 0)'), ('South', 'POINT(0 -1)'); SELECT name, ST_AsText(point) FROM points; 61. 62. Line Creation CREATE TABLE lines (name varchar); SELECT AddGeometryColumn('lines', 'line', -1, 'LINESTRING', 2); INSERT INTO lines VALUES ('North West', 'LINESTRING(0 0,-1 1)'), ('North East', 'LINESTRING(0 0, 1 1)'), ('South West', 'LINESTRING(0 0,-1 -1)'), ('South East', 'LINESTRING(0 0,1 -1)'); SELECT name, ST_AsText(line) FROM lines; 63. 64. Unconstrained Geometries INSERT INTO points VALUES ('Not a point', 'LINESTRING(1 1, -1 -1)'), ('3d point', 'POINT(0 0 3)'), ('WGS84 point', ST_SetSRID('POINT(0 1)', 4326)); 65. 66. Constrained Geometries INSERT INTO lines VALUES ('Not a line', 'POINT(0 0)'); INSERT INTO lines VALUES ('4d line', 'LINESTRING(1 1 3 0, -1 -1 0 3.4)'); INSERT INTO lines VALUES ('WGS84 line', ST_SetSRID('LINESTRING(-1 1,1 -1)',4326)); 67. 68. 69. 70. 71. Metadata Table SELECT * FROM geometry_columns; 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. Accessing Geometry Components Multi-geometry ST_NumGeometries(geometry) ST_GeometryN(geometry, index) 83. Accessing Geometry Components Multi-geometry Polygon ST_NumInteriorRings(geometry) ST_NRings(geometry) ST_ExteriorRing(geometry) ST_InteriorRingN(geometry, index) 84. Accessing Geometry Components Multi-geometry Polygon Linestring ST_NumPoints(geometry) ST_NPoints(geometry) ST_PointN(geometry,index) 85. Accessing Geometry Components Multi-geometry Polygon Linestring Point ST_X(geometry) ST_Y(geometry) ST_Z(geometry) ST_M(geometry) 86. Length SELECT ST_Length(ST_GeomFromText( 'LINESTRING(0 0,5 0,5 10)')); 87. 88. Length SELECT ST_Length(ST_GeomFromText( 'LINESTRING(0 0,5 0,5 10)')); SELECT ST_Length(ST_GeomFromText( 'LINESTRING(0 0 0,5 0 3,5 10 5)')); 89. 90. Length SELECT ST_Length(ST_GeomFromText( 'LINESTRING(0 0,5 0,5 10)')); SELECT ST_Length(ST_GeomFromText( 'LINESTRING(0 0 0,5 0 3,5 10 5)')); SELECT ST_Length3D(ST_GeomFromText( 'LINESTRING(0 0 0,5 0 3,5 10 5)')); 91. 92. Length SELECT ST_Length2D_Spheroid(g, 'SPHEROID["GRS 1980",6378137,298.257222101]'), ST_Length3D_Spheroid(g, 'SPHEROID["GRS 1980",6378137,298.257222101]') FROM ( VALUES ( ST_GeomFromEWKT('LINESTRING(151.1205 -33.7145 0,151.1218 -33.7087 54)') ) ) AS query(g); 93. 94. Length - Perimeter SELECT ST_Perimeter(ST_GeomFromEWKT(g)) FROM ( VALUES ('POLYGON((-2 -2 0,2 -2 1,2 2 2,-2 2 1,-2 -2 0))'), ('POLYGON((-2 -2,2 -2,2 2,-2 2,-2 -2),(1 1,-1 1,-1 -1,1 -1,1 1))') ) AS query(g); 95. 96. Length - Perimeter SELECT ST_Length( ST_ExteriorRing( ST_GeomFromEWKT( 'POLYGON((-2 -2,2 -2,2 2,-2 2,-2 -2),(1 1,-1 1,-1 -1,1 -1,1 1))' ) ) ); 97. 98. Area SELECT ST_Area(ST_GeomFromEWKT(g)) FROM ( VALUES ('POLYGON((-2 -2 0,2 -2 1,2 2 2,-2 2 1,-2 -2 0))'), ('POLYGON(( -2 -2,2 -2,2 2,-2 2,-2 -2 ),( 1 1,-1 1,-1 -1,1 -1,1 1 ))') ) AS query(g); 99. 100. Distance SELECT ST_Distance(ST_GeomFromEWKT('POINT(0 5)'), ST_GeomFromEWKT('LINESTRING(-2 2,2 2)')); 101. 102. Distance SELECT ST_Distance_Sphere(a, b), ST_Distance_Spheroid(a, b, 'SPHEROID["GRS 1980",6378137,298.257222101]') FROM ( VALUES ( ST_GeomFromText('POINT(151.1205 -33.7145)'), ST_GeomFromText('POINT(151.1218 -33.7087)') ) ) AS query (a, b); 103. 104. Within a Distance SELECT namelow FROM jacksonco_streets, medford_parks WHERE ST_Distance(medford_parks.the_geom, jacksonco_streets.the_geom) < 5000 / 0.3048 AND medford_parks.name = 'Hawthorne Park / Pool'; 105. 106. Within a Distance SELECT namelow FROM jacksonco_streets, medford_parks WHERE ST_DWithin(medford_parks.the_geom, jacksonco_streets.the_geom, 5000 / 0.3048) AND medford_parks.name = 'Hawthorne Park / Pool'; 107. 108. Spatial Indexing CREATE INDEX jacksonco_streets_gix ON jacksonco_streets USING GIST (the_geom); 109. Spatial Indexing CREATE INDEX jacksonco_streets_gix ON jacksonco_streets USING GIST (the_geom); 110. Spatial Indexing SELECT namelow FROM jacksonco_streets, medford_parks WHERE jacksonco_streets.the_geom && medford_parks.the_geom AND medford_parks.name = 'Hawthorne Park / Pool'; 111. 112. 113. Spatial Indexing SELECT namelow FROM jacksonco_streets, medford_parks WHERE ST_DWithin(medford_parks.the_geom, jacksonco_streets.the_geom, 5000 / 0.3048) AND medford_parks.name = 'Hawthorne Park / Pool'; 114. 115. Creating Indices CREATE INDEX jacksonco_schools_gix ON jacksonco_schools USING GIST (the_geom); CREATE INDEX jacksonco_taxlots_gix ON jacksonco_taxlots USING GIST (the_geom); CREATE INDEX medford_buildings_gix ON medford_buildings USING GIST (the_geom); CREATE INDEX medford_citylimits_gix ON medford_citylimits USING GIST (the_geom); CREATE INDEX medford_hydro_gix ON medford_hydro USING GIST (the_geom); CREATE INDEX medford_parks_gix ON medford_parks USING GIST (the_geom); CREATE INDEX medford_planzone_gix ON medford_planzone USING GIST (the_geom); CREATE INDEX medford_stormdrain_gix ON medford_stormdrain USING GIST (the_geom); CREATE INDEX medford_wards_gix ON medford_wards USING GIST (the_geom); CREATE INDEX medford_wetlands_gix ON medford_wetlands USING GIST (the_geom); CREATE INDEX medford_zoning_gix ON medford_zoning USING GIST (the_geom); CREATE INDEX tracts_gix ON tracts USING GIST (the_geom); 116. Vacuum Vacuum Recover or reuse disk space from obsolete rows Analyze Update query planner statistics Cluster Rewrite tables based on index ordering 117. Spatial Joins Within SELECT name FROM jacksonco_schools, medford_citylimits WHERE ST_Within(jacksonco_schools.the_geom, medford_citylimits.the_geom); 118. 119. Spatial Joins Intersect SELECT SUM(ST_Length(jacksonco_streets.the_geom)) FROM jacksonco_streets, medford_citylimits WHERE ST_Intersects(jacksonco_streets.the_geom,medford_citylimits.the_geom); 120. 121. Spatial Joins Intersect SELECT jacksonco_schools.name, white_pop_1race * 1.0 / total_pop AS white_pop, black_pop_1race * 1.0 / total_pop AS black_pop, aindian_1race * 1.0 / total_pop AS indian_pop, asian_1race * 1.0 / total_pop AS asian_popp, hawaiian_1race * 1.0 / total_pop AS hawaiian_pop FROM tracts, race, jacksonco_schools WHERE tracts.ctidfp00 = race.geography_id2 AND ST_Intersects(tracts.the_geom, jacksonco_schools.the_geom); 122. 123. Spatial Operators ST_Contains(geomA, geomB) ST_ContainsProperly(geomA, geomB) ST_Covers(geomA, geomB) ST_CoveredBy(geomA, geomB) ST_Crosses(geomA, geomB) ST_Disjoint(geomA, geomB) ST_Intersects(geomA, geomB) ST_Overlaps(geomA, geomB) ST_Touches(geomA, geomB) ST_Within(geomA, geomB) 124. Projecting Data SELECT SUM(ST_Length(the_geom)) FROM jacksonco_streets WHERE namelow = 'E Main St'; 125. 126. Projecting Data SELECT SUM(ST_Length(ST_Transform(the_geom, 2839))) FROM jacksonco_streets WHERE namelow = 'E Main St'; 127. 128. 129. 130. 131. 132. 133. 134. Exercises Twenty minutes to try the exercises 135. Exercises How big is the largest building in Medford in square feet? In square metres? 136. Exercises How big is the largest building in Medford in square feet? SELECT ST_Area(the_geom) AS areaFROM medford_buildingsORDER BY area DESC LIMIT 1; In square metres? SELECT ST_Area(ST_Transform(the_geom, 2839))AS area FROM medford_buildingsORDER BY area DESC LIMIT 1; 137. 138. 139. Exercises What is the elevation of the 'South Medford' high school building? 140. Exercises What is the elevation of the 'South Medford' high school building? SELECT medford_buildings.elevationFROM medford_buildings, jacksonco_schoolsWHERE ST_Within(jacksonco_schools.the_geom, medford_buildings.the_geom)AND jacksonco_schools.name = 'South Medford'; 141. 142. Exercises What are the expected percentages of children in poverty at each school with a Kindergarten class? 143. Exercises What are the expected percentages of children in poverty at each school with a Kindergarten class? SELECT jacksonco_schools.name,poverty.poverty_level_under5yearsFROM jacksonco_schools, tracts, povertyWHERE tracts.ctidfp00 = geography_id2 ANDST_Within( jacksonco_schools.the_geom, tracts.the_geom )AND jacksonco_schools.grade ~ 'K'; 144. 145. Exercises What is the length of 'E Main St'? 146. Exercises What is the length of 'E Main St'? SELECT Sum(ST_Length(the_geom))FROM jacksonco_streetsWHERE legalname ~* 'E Main St'; 147. 148. Exercises How much park area is there within the Medford city limits? 149. Exercises How much park area is there within the Medford city limits? SELECT SUM(ST_Area(medford_parks.the_geom))FROM medford_parks, medford_citylimitsWHERE ST_Intersects(medford_parks.the_geom, medford_citylimits.the_geom); 150. 151. Exercises How many buildings are located within wetlands? 152. Exercises How many buildings are located within wetlands? SELECT count(*)FROM medford_buildings, medford_wetlandsWHERE ST_Within(medford_buildings.the_geom, medford_wetlands.the_geom); 153. 154. Exercises Which school is farthest from a park? Which is closest? 155. Exercises Which school is farthest from a park? SELECT jacksonco_schools.name, ST_Distance(jacksonco_schools.the_geom, medford_parks.the_geom) AS distanceFROM jacksonco_schools, medford_parksORDER BY distance desc LIMIT 1; Which is closest? SELECT jacksonco_schools.name, ST_Distance(jacksonco_schools.the_geom, medford_parks.the_geom) AS distanceFROM jacksonco_schools, medford_parksORDER BY distance asc LIMIT 1; 156. 157. 158. Exercises Which schools have the most park area within 400 feet? Within 1 km? 159. Exercises Which schools have the most park area within 400 feet? SELECT jacksonco_schools.name, SUM(ST_Area(medford_parks.the_geom)) AS areaFROM jacksonco_schools, medford_parksWHERE ST_DWithin(jacksonco_schools.the_geom, medford_parks.the_geom, 400)GROUP BY jacksonco_schools.nameORDER BY area DESC; Within 1 km? 160. 161. Exercises Which schools have the most park area within 400 feet? Within 1 km? SELECT jacksonco_schools.name, SUM(ST_Area(medford_parks.the_geom)) AS areaFROM jacksonco_schools, medford_parksWHERE ST_DWithin(ST_Transform(jacksonco_schools.the_geom, 2839), ST_Transform(medford_parks.the_geom, 2839), 1000)GROUP BY jacksonco_schools.nameORDER BY area DESC; 162. 163. Exercises Which schools have the most park area within 400 feet? Within 1 km? SELECT jacksonco_schools.name, SUM(ST_Area(medford_parks.the_geom)) AS areaFROM jacksonco_schools, medford_parksWHERE ST_DWithin(jacksonco_schools.the_geom, medford_parks.the_geom, 1000 / 0.3048)GROUP BY jacksonco_schools.nameORDER BY area DESC; 164. 165. Exercises What are the expected percentages of unmarried families for each school? 166. Exercises What are the expected percentages of unmarried families for each school? SELECT s.name, 100.0 * t.hh_unmarried / t.hh_totalFROM jacksonco_schools s, unmarriedbytract tWHERE ST_Contains(t.the_geom, s.the_geom); 167. 168. Exercises Howmany storm drains are within 500 feet of 'Bear Creek'? 169. Exercises Howmany storm drains are within 500 feet of 'Bear Creek'? SELECT count(*)FROM medford_stormdrain, medford_hydroWHERE ST_DWithin(medford_hydro.the_geom, medford_stormdrain.the_geom, 500)AND medford_hydro.stream_nam = 'Bear Creek'; 170. 171. Tuning PostgreSQL for Spatial C:Program FilesPostgreSQL8.4datapostgresql.conf pgAdmin provides aConfiguration Editor File ->Open postgresql.conf 172. 173. 174. shared_buffers Determines the amount of memory that is shared by back-end processes Default Value = 32MB Recommended Value = 500MB 175. 176. work_mem Defines the amount of memory that a single process can use for sorting or hash operations Default Value = 1MB Recommended Value = 16MB 177. 178. maintenance_work_mem Defines the amount of memory used for maintenance operations, such as vacuuming, index and foreign key creation. Default Value = 16MB Recommended Value = 16MB Can be set per-session before specific operations SET maintenance_work_mem TO '128MB'; VACUUM ANALYZE; SET maintenance_work_mem TO '16MB'; 179. 180. wal_buffers Amount of memory used by thewrite-ahead log(WAL). Default Value = 64kB Recommended Value = 1MB 181. 182. checkpoint_segments Sets the number of log file segments that can be filled between WAL logs are flushed to disk. Default Value = 3 Recommended Value = 6 183. 184. random_page_cost Represents thecostof random page access from disk. Default Value = 4.0 Recommended Value = 2.0 185. 186. seq_page_cost Represents the cost of a sequential page access from disk. Default Value = 1.0 Recommended Value = 1.0 187. 188. Query Plans Set of steps that PostgreSQL can use to generate the results of a query Multiple query plans are produced, costed and selected Cost is based on configuration parameters such asrandom_page_costandseq_page_cost PostgreSQL and pgAdmin provides a way to view the victorious query plan 189. 190. Test Query SELECT namelowFROM jacksonco_streets, medford_citylimits WHERE ST_Intersects(jacksonco_streets.the_geom, medford_citylimits.the_geom) GROUP BY namelow; 191. 192. Sequence Scan Linear scan of every row in the table(medford_citylimits) Can evaluate filter conditions on scan 193. Index Scan Linear scan of an index(jacksonco_streets_gix) Evaluates the bounding box comparison during scan (jacksonco_streets.the_geom && medford_citylimits.the_geom) Comparison is evaluated for each result of the previous scan Execution time overlaps the sequence scan 194. Nested Loop Performs the join between the two scans One (sequence scan) is the outer loop Other (index scan) is the inner loop Further filter is evaluated Execution time includes index scan 195. Hash Aggregate Performs the grouping based on an attribute Only available for attributes with a hashing algorithm Executes after the nested loop completes 196. Visualisation uDig is used for visualisation It is available inc:workshopsPostGISsoftwareudig Double-click onudig.bat 197. 198. 199. 200. 201. 202. 203. 204. 205. 206. Add Layers medford_hydro medford_parks medford_citylimits agebysexbytract 207. 208. 209. 210. 211. 212. 213. 214. 215. 216. 217. 218. 219. 220. Validity Simple Features for SQL provides strict definitions of a valid feature Some functions require validity to perform as expected ST_IsValid(geometry) is provided to ensure feature validity 221. Validity Simple Features for SQL provides strict definitions of a valid feature Some functions require validity to perform as expected ST_IsValid(geometry) is provided to ensure feature validity SELECT count(*), ST_IsValid(the_geom) FROM jacksonco_taxlots GROUP BY ST_IsValid; 222. 223. Fixing Validity UPDATE jacksonco_taxlots SET the_geom = ST_Multi(ST_Buffer(the_geom, 0)); SELECT count(*), ST_IsValid(the_geom) FROM jacksonco_taxlots GROUP BY ST_IsValid; 224. 225. Equality PostGIS provides three different levels ofequality Exactly Equal Spatially Equal BBox Equal 226. Equality CREATE TABLE polygons (name varchar, poly geometry); INSERT INTO polygons VALUES ('Polygon 1', 'POLYGON((-1 1.732,1 1.732,2 0,1 -1.732, -1 -1.732,-2 0,-1 1.732))'), ('Polygon 2', 'POLYGON((-1 1.732,-2 0,-1 -1.732,1 -1.732, 2 0,1 1.732,-1 1.732))'), ('Polygon 3', 'POLYGON((1 -1.732,2 0,1 1.732,-1 1.732, -2 0,-1 -1.732,1 -1.732))'), ('Polygon 4', 'POLYGON((-1 1.732,0 1.732, 1 1.732,1.5 0.866, 2 0,1.5 -0.866,1 -1.732,0 -1.732,-1 -1.732,-1.5 -0.866, -2 0,-1.5 0.866,-1 1.732))'), ('Polygon 5', 'POLYGON((-2 -1.732,2 -1.732,2 1.732, -2 1.732,-2 -1.732))'); 227. 228. Exactly Equal Point-by-point comparison of two geometries SELECT a.name, b.name, CASE WHEN a.poly ~= b.poly THEN 'Exactly Equal' ELSE 'Not Exactly Equal' end FROM polygons as a, polygons as b; 229. 230. Spatially Equal Tests the topology of two geometries for equality SELECT a.name, b.name,CASE WHEN ST_Equals(a.poly, b.poly) THEN 'Spatially Equal' ELSE 'Not Equal' end FROM polygons as a, polygons as b; 231. 232. Equal Bounds Tests for equality of the bounding box SELECT a.name, b.name, CASE WHEN a.poly = b.poly THEN 'Equal Bounds' ELSE 'Non-equal Bounds' end FROM polygons as a, polygons as b; 233. 234. Advanced Material Advanced Functions Aggregates / Deaggregates Processing Set Operations Performance Tools Manipulating the Query Planner Denormalization Data Partitioning 235. Using uDig uDig lacks adynamic querycapability Queries can be viewed by creating views CREATE VIEW example1 AS SELECT * FROM (VALUES(ST_GeomFromText( 'MULTIPOLYGON(((-77 56,-52 18,-88 -27,-10 -13,-11 38,-77 56)))')), (ST_GeomFromText('MULTIPOLYGON(((-49 63,-32 24,-39 -7,-66 -19,-72 -9,-74 31,-49 63)))'))) AS query(the_geom);SELECT populate_geometry_columns(); 236. 237. ST_Union(geometry) Merges geometries into a single (often multi-) geometry Support aggregate form as well as: ST_Union(geomA, geomB) ST_Union(geomArray[ ]) 238. ST_Union(geometry) SELECT ST_AsText(ST_Union(st_geomfromtext)) FROM (SELECT ST_GeomFromText( 'MULTIPOLYGON(((-77 56,-52 18,-88 -27,-10 -13,-11 38,-77 56)))') UNION ALL SELECT ST_GeomFromText( 'MULTIPOLYGON(((-49 63,-32 24,-39 -7,-66 -19,-72 -9,-74 31,-49 63)))') ) as a; 239. 240. ST_Collect(geometry) Returns a single multi-geometry or collection, but performs no merging of geometries Faster that ST_Union Supports aggregate form as well as: ST_Collect(geomA, geomB) ST_Collect(geomArray[ ]) 241. ST_Collect(geometry) SELECT ST_AsText(ST_Collect(the_geom)) FROM (SELECT 'LINESTRING(0 0, 0 1)'::geometry the_geom UNION ALL SELECT 'LINESTRING(1 0, 1 1)'::geometry the_geom UNION ALL SELECT 'LINESTRING(0 0,1 0)'::geometry the_geom UNION ALL SELECT 'LINESTRING(1 1, 0 1)'::geometry the_geom) as a; 242. 243. ST_Polygonize(geometry) Generates a geometry containing all polygons that can be built from the input linework 244. ST_Polygonize(geometry) SELECT ST_AsText(ST_Polygonize(the_geom)) FROM (SELECT 'LINESTRING(0 0, 0 1)'::geometry the_geom UNION ALL SELECT 'LINESTRING(1 0, 1 1)'::geometry the_geom UNION ALL SELECT 'LINESTRING(0 0,1 0)'::geometry the_geom UNION ALL SELECT 'LINESTRING(1 1, 0 1)'::geometry) as a; 245. 246. ST_Dump(geometry) Splits multi-geometries and collections into a set of simple geometries Inverse ST_Collect (ish) Provides an index of the geometry within the collection (path) and the geometry itself (ST_Dump(the_geom)).geom (ST_Dump(the_geom)).path[1] 247. ST_Dump(geometry) SELECT ST_AsText((ST_Dump(the_geom)).geom) FROM jacksonco_taxlots WHERE gid = 90917; 248. 249. ST_DumpRings(geometry) Returns a set of polygons without holes Each polygon is one of the rings of the input polygon Also includes a path and geom components (ST_DumpRings(geom)).geom (ST_DumpRings(geom)).path[1] 250. Set Operations Produce results based on inclusion or exclusion of points from a geometry A geometry includes all point on or within its boundary Excludes all other points 251. Set Operations Produce results based on inclusion or exclusion of points from a geometry Point includes only the point itself 252. Set Operations Produce results based on inclusion or exclusion of points from a geometry Linestring includes the two end points and all point along its length 253. Set Operations Produce results based on inclusion or exclusion of points from a geometry Polygon Includes all exterior and interior rings Includes all points contained within the exterior ring and not contained within the interior rings Excludes all points contained within interior rings 254. Set Operations MULTIPOLYGON(((-77 56,-52 18,-88 -27,-10 -13,-11 38,-77 56))) MULTIPOLYGON(((-49 63,-32 24,-39 -7,-66 -19,-72 -9,-74 31,-49 63))) 255. ST_Union(geomA, geomB) Same as the ST_Union(geometry) aggregate Any point included in either geometry is included in the result SELECT ST_AsText(ST_Union( ST_GeomFromText( 'MULTIPOLYGON(((-77 56,-52 18,-88 -27,-10 -13,-11 38,-77 56)))'), ST_GeomFromText( 'MULTIPOLYGON(((-49 63,-32 24,-39 -7,-66 -19,-72 -9,-74 31,-49 63)))'))); 256. 257. 258. ST_Difference(geomA, geomB) All point included in geomA that are not included in geomB Non-communicative; the order of geomA and geomB matters SELECT ST_AsText(ST_Difference( ST_GeomFromText( 'MULTIPOLYGON(((-77 56,-52 18,-88 -27,-10 -13,-11 38,-77 56)))'), ST_GeomFromText( 'MULTIPOLYGON(((-49 63,-32 24,-39 -7,-66 -19,-72 -9,-74 31,-49 63)))'))); 259. 260. 261. ST_SymDifference(geomA, geomB) All points that or included in only one of geomA and geomB, but not both ST_Union(ST_Difference(A,B),ST_Difference(B,A)) SELECT ST_AsText(ST_SymDifference( ST_GeomFromText( 'MULTIPOLYGON(((-77 56,-52 18,-88 -27,-10 -13,-11 38,-77 56)))'), ST_GeomFromText( 'MULTIPOLYGON(((-49 63,-32 24,-39 -7,-66 -19,-72 -9,-74 31,-49 63)))'))); 262. 263. 264. ST_Intersection(geomA, geomB) All points included in both geomA and geomB SELECT ST_AsText(ST_Intersection( ST_GeomFromText( 'MULTIPOLYGON(((-77 56,-52 18,-88 -27,-10 -13,-11 38,-77 56)))'), ST_GeomFromText( 'MULTIPOLYGON(((-49 63,-32 24,-39 -7,-66 -19,-72 -9,-74 31,-49 63)))'))); 265. 266. 267. ST_Buffer(geometry, distance) Returns a geometry containing an area withdistanceof the input geometry. Can take a third argument defining number of segments used to approximate a quarter circle (defaults to 8) SELECT ST_AsText(ST_Buffer(ST_GeomFromText( 'LINESTRING(-2 -2,-2 2,2 2,2 4)'), 1)); 268. 269. 270. ST_ConvexHull(geometry) Returns a polygon that encloses the input geometry, removing all possible concave angles Analogous to 'shrink wrapping' the geometry SELECT ST_AsText(ST_ConvexHull( 'LINESTRING(-2 -2,-2 2,2 2,2 4)')); 271. 272. 273. ST_SnapToGrid(...) Snaps every point in the input geometry to the defined grid Allows you to: control the precision of data for reliable comparison reduce size of data Numerous variants to give you what you need 274. ST_SnapToGrid(...) Numerous variants to give you what you need ST_SnapToGrid(geom, size) ST_SnapToGrid(geom, sizeX, sizeY) ST_SnapToGrid(geom, originX, originY, sizeX, sizeY) ST_SnapToGrid(geom, originPoint, sizeX, sizeY, sizeZ, sizeM) 275. ST_Simplify(geom, tolerance) Creates a simpler geometry Simplifications are made to ensure that the new line deviates from the original by less that the tolerance 276. ST_Simplify(geom, tolerance) The line is simplified by producing a candidate line connecting the end points 277. ST_Simplify(geom, tolerance) The greatest distance between the candidate line and the original line is calculated If the distance is greater than the tolerance, the candidate line is rejected and two candidate lines are created 278. ST_Simplify(geom, tolerance) Each new candidate line is tested in the same manner as before When the distances is less than the tolerance, the candidate line is accepted 279. ST_Simplify(geom, tolerance) The final result is a geometry made up of all accepted candidate lines 280. ST_Simplify(geom, tolerance) SELECT ST_AsText(geom) AS original, ST_AsText(ST_Simplify(geom, 3)) AS "3", ST_AsText(ST_Simplify(geom, 2.9)) AS "2.9" FROM ( SELECT ST_GeomFromText('LINESTRING(0 0,3 2.5,05)')AS geom) AS a; 281. 282. ST_SimplifyPreserveTopology Same algorithm as ST_Simplify Will not change the type of geometry SELECT ST_AsText(geom) AS original, ST_AsText(ST_Simplify(geom, 2)) AS Simplify, ST_AsText(ST_SimplifyPreserveTopology(geom, 2)) AS PreserveTopology FROM ( SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))') AS geom) AS a; 283. 284. Query Planner Manipulation Query planner only considers approved actions Various execution paths can be disabled Cost estimates can be manipulated on a per-session basis 285. Denormalisation Split feature types into multiple tables based on known or expected access patterns 286. Denormalisation Split feature types into multiple tables based on known or expected access patterns Roads are visualised with different style classes and rendered at different scales 287. 288. Partitioning Data partitioning complicates things Updates need to be split across all tables Queries need to be directed at the appropriate table(s) Keeping both normalised and denormalised tables creates huge redundancy Partitioning addresses these problems Stores data in denormalised tables Provides a normalised interface to handle queries across the feature type 289. Fin Workshop Evaluations are Online (url removed) This material is made available under theCreative Commons Attribution-ShareAlike 3.0 licence http://creativecommons.org/licenses/by-sa/3.0/us/