SlideShare a Scribd company logo
1 of 289
Introduction to PostGIS Presented by: Mark Leslie Mike Pumphrey Paul Ramsey
Workshop Format Interactive C:orkshopsntro_to_postgis http://localhost/postgis/workshop Hands On All examples are executable Copy and Paste from HTML Exercises Answers will be provided (eventually) Try This  sections for greater challenge
What is a Spatial Database? Spatial Data Types Point a single coordinate of two to four dimensions
What is a Spatial Database? Spatial Data Types Linestring a set of two or more coordinates linear interpretation of path between coordinates
What is a Spatial Database? Spatial Data Types Linearring a linestring with three or more coordinates the start and end points are the same
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
What is a Spatial Database? Spatial Data Types Multi-geometries (Multipoint, Multilinestring, Multipolygon) a set of like geometries
What is a Spatial Database? Spatial Data Types Geometrycollection a set of various (unmatched) geometries
What is a Spatial Database? Spatial Data Types Spatial Indexing R-tree Quadtree Grid-based
What is a Spatial Database? Spatial Data Types Spatial Indexing Spatial Functions Construction Serialisation Predicates Analysis Accessors Builders Aggregates
What is PostGIS? Spatial Extensions for PostgreSQL Provides Spatial Data Type Provides Spatial Indexing Provides Spatial Functions
What is PostGIS? Spatial Extensions for PostgreSQL PostgreSQL Extensions for Spatial ACID transaction guarantees Enterprise reliability Crash recovery Hot backup Replication SQL support
PostGIS History Initially released May 2001 with only load/store and index support. Functions added based on  Simple 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
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
PostgreSQL Setup Installing PostgreSQL Software provided it C:orkshopsostGISoftware 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
PostgreSQL Installation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
PostGIS Documentation
Creating a Spatial Database
 
 
 
 
 
 
 
 
Loading Data
Loading Data Change to  C:orkshopsostGISata Execute  set_environment.bat
 
Load the Parks Shapefile shp2pgsql -s 2270 medford_parks.shp medford_parks > medford_parks.sql psql -f medford_parks.sql workshop
 
 
 
Load the Schools Shapefile shp2pgsql -s 2270 -D jacksonco_schools.shp jacksonco_schools > jacksonco_schools.sql psql -f jacksonco_schools.sql workshop
 
 
Load Additional Data psql -f medford.sql workshop
 
Geometries –  Creating and Manipulating Creating simple geometries Consistent geometries through constraints Geometry types and output Accessing geometry components Measurement Functions
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;
 
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;
 
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));
 
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));
 
 
 
 
Metadata Table SELECT * FROM geometry_columns;
 
 
 
 
 
 
 
 
 
 
Accessing Geometry Components Multi-geometry ST_NumGeometries(geometry) ST_GeometryN(geometry, index)
Accessing Geometry Components Multi-geometry Polygon ST_NumInteriorRings(geometry) ST_NRings(geometry) ST_ExteriorRing(geometry) ST_InteriorRingN(geometry, index)
Accessing Geometry Components Multi-geometry Polygon Linestring ST_NumPoints(geometry) ST_NPoints(geometry) ST_PointN(geometry,index)
Accessing Geometry Components Multi-geometry Polygon Linestring Point ST_X(geometry) ST_Y(geometry) ST_Z(geometry) ST_M(geometry)
Length SELECT ST_Length(ST_GeomFromText( 'LINESTRING(0 0,5 0,5 10)'));
 
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)'));
 
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)'));
 
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);
 
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);
 
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))' ) ) );
 
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);
 
Distance SELECT ST_Distance(ST_GeomFromEWKT('POINT(0 5)'), ST_GeomFromEWKT('LINESTRING(-2 2,2 2)'));
 
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);
 
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';
 
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';
 
Spatial Indexing CREATE INDEX jacksonco_streets_gix ON jacksonco_streets USING GIST (the_geom);
Spatial Indexing CREATE INDEX jacksonco_streets_gix ON jacksonco_streets USING GIST (the_geom);
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';
 
 
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';
 
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);
Vacuum Vacuum Recover or reuse disk space from obsolete rows Analyze Update query planner statistics Cluster Rewrite tables based on index ordering
Spatial Joins – Within SELECT name FROM jacksonco_schools, medford_citylimits WHERE ST_Within(jacksonco_schools.the_geom, medford_citylimits.the_geom);
 
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);
 
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);
 
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)
Projecting Data SELECT SUM(ST_Length(the_geom)) FROM jacksonco_streets WHERE namelow = 'E Main St';
 
Projecting Data SELECT SUM(ST_Length(ST_Transform(the_geom, 2839))) FROM jacksonco_streets WHERE namelow = 'E Main St';
 
 
 
 
 
 
 
Exercises Twenty minutes to try the exercises
Exercises How big is the largest building in Medford in square feet? In square metres?
Exercises How big is the largest building in Medford in square feet? SELECT ST_Area(the_geom) AS area  FROM medford_buildings  ORDER BY area DESC LIMIT 1; In square metres? SELECT ST_Area(ST_Transform(the_geom, 2839))  AS area FROM medford_buildings  ORDER BY area DESC LIMIT 1;
 
 
Exercises What is the elevation of the 'South Medford' high school building?
Exercises What is the elevation of the 'South Medford' high school building? SELECT medford_buildings.elevation  FROM medford_buildings, jacksonco_schools  WHERE ST_Within(jacksonco_schools.the_geom, medford_buildings.the_geom)  AND jacksonco_schools.name = 'South Medford';
 
Exercises What are the expected percentages of children in poverty at each school with a Kindergarten class?
Exercises What are the expected percentages of children in poverty at each school with a Kindergarten class? SELECT jacksonco_schools.name,  poverty.poverty_level_under5years  FROM jacksonco_schools, tracts, poverty  WHERE tracts.ctidfp00 = geography_id2 AND  ST_Within( jacksonco_schools.the_geom, tracts.the_geom )  AND jacksonco_schools.grade ~ 'K';
 
Exercises What is the length of 'E Main St'?
Exercises What is the length of 'E Main St'? SELECT Sum(ST_Length(the_geom))  FROM jacksonco_streets  WHERE legalname ~* 'E Main St';
 
Exercises How much park area is there within the Medford city limits?
Exercises How much park area is there within the Medford city limits? SELECT SUM(ST_Area(medford_parks.the_geom))  FROM medford_parks, medford_citylimits  WHERE ST_Intersects(medford_parks.the_geom, medford_citylimits.the_geom);
 
Exercises How many buildings are located within wetlands?
Exercises How many buildings are located within wetlands? SELECT count(*)  FROM medford_buildings, medford_wetlands  WHERE ST_Within(medford_buildings.the_geom, medford_wetlands.the_geom);
 
Exercises Which school is farthest from a park? Which is closest?
Exercises Which school is farthest from a park? SELECT jacksonco_schools.name, ST_Distance(jacksonco_schools.the_geom, medford_parks.the_geom) AS distance  FROM jacksonco_schools, medford_parks  ORDER BY distance desc LIMIT 1; Which is closest? SELECT jacksonco_schools.name, ST_Distance(jacksonco_schools.the_geom, medford_parks.the_geom) AS distance  FROM jacksonco_schools, medford_parks  ORDER BY distance asc LIMIT 1;
 
 
Exercises Which schools have the most park area within 400 feet? Within 1 km?
Exercises Which schools have the most park area within 400 feet? SELECT jacksonco_schools.name, SUM(ST_Area(medford_parks.the_geom)) AS area  FROM jacksonco_schools, medford_parks  WHERE ST_DWithin(jacksonco_schools.the_geom, medford_parks.the_geom, 400)  GROUP BY jacksonco_schools.name  ORDER BY area DESC; Within 1 km?
 
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 area  FROM jacksonco_schools, medford_parks  WHERE ST_DWithin(ST_Transform(jacksonco_schools.the_geom, 2839), ST_Transform(medford_parks.the_geom, 2839), 1000)  GROUP BY jacksonco_schools.name  ORDER BY area DESC;
 
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 area  FROM jacksonco_schools, medford_parks  WHERE ST_DWithin(jacksonco_schools.the_geom, medford_parks.the_geom, 1000 / 0.3048)  GROUP BY jacksonco_schools.name  ORDER BY area DESC;
 
Exercises What are the expected percentages of unmarried families for each school?
Exercises What are the expected percentages of unmarried families for each school? SELECT s.name, 100.0 * t.hh_unmarried / t.hh_total  FROM jacksonco_schools s, unmarriedbytract t  WHERE ST_Contains(t.the_geom, s.the_geom);
 
Exercises How  many storm drains are within 500 feet of 'Bear Creek'?
Exercises How  many storm drains are within 500 feet of 'Bear Creek'? SELECT count(*)  FROM medford_stormdrain, medford_hydro  WHERE ST_DWithin(medford_hydro.the_geom, medford_stormdrain.the_geom, 500)  AND medford_hydro.stream_nam = 'Bear Creek';
 
Tuning PostgreSQL for Spatial C:rogram FilesostgreSQL.4ataostgresql.conf pgAdmin provides a  Configuration Editor File ->Open postgresql.conf
 
 
shared_buffers Determines the amount of memory that is shared by back-end processes Default Value = 32MB Recommended Value = 500MB
 
work_mem Defines the amount of memory that a single process can use for sorting or hash operations Default Value = 1MB Recommended Value = 16MB
 
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';
 
wal_buffers Amount of memory used by the  write-ahead log  (WAL). Default Value = 64kB Recommended Value = 1MB
 
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
 
random_page_cost Represents the  cost  of random page access from disk. Default Value = 4.0 Recommended Value = 2.0
 
seq_page_cost Represents the cost of a sequential page access from disk. Default Value = 1.0 Recommended Value = 1.0
 
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 as  random_page_cost  and  seq_page_cost PostgreSQL and pgAdmin provides a way to view the victorious query plan
 
Test Query SELECT namelow  FROM jacksonco_streets, medford_citylimits WHERE ST_Intersects(jacksonco_streets.the_geom, medford_citylimits.the_geom) GROUP BY namelow;
 
Sequence Scan Linear scan of every row in the table  (medford_citylimits) Can evaluate filter conditions on scan
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
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
Hash Aggregate Performs the grouping based on an attribute Only available for attributes with a hashing algorithm Executes after the nested loop completes
Visualisation uDig is used for visualisation It is available in  c:orkshopsostGISoftwaredig Double-click on  udig.bat
 
 
 
 
 
 
 
 
 
Add Layers medford_hydro medford_parks medford_citylimits agebysexbytract
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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;
 
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;
 
Equality PostGIS provides three different levels of  equality Exactly Equal Spatially Equal BBox Equal
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))');
 
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;
 
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;
 
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;
 
Advanced Material Advanced Functions Aggregates / Deaggregates Processing Set Operations Performance Tools Manipulating the Query Planner Denormalization Data Partitioning
Using uDig uDig lacks a  dynamic query  capability 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();
 
ST_Union(geometry) Merges geometries into a single (often multi-) geometry Support aggregate form as well as: ST_Union(geomA, geomB) ST_Union(geomArray[ ])
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;
 
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[ ])
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;
 
ST_Polygonize(geometry) Generates a geometry containing all polygons that can be built from the input linework
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;
 
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]
ST_Dump(geometry) SELECT ST_AsText((ST_Dump(the_geom)).geom) FROM jacksonco_taxlots WHERE gid = 90917;
 
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]
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
Set Operations Produce results based on inclusion or exclusion of points from a geometry Point includes only the point itself
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
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
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)))
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)))')));
 
 
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)))')));
 
 
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)))')));
 
 
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)))')));
 
 
ST_Buffer(geometry, distance) Returns a geometry containing an area with  distance  of 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));
 
 
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)'));
 
 
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
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)
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
ST_Simplify(geom, tolerance) The line is simplified by producing a candidate line connecting the end points
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
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
ST_Simplify(geom, tolerance) The final result is a geometry made up of all accepted candidate lines
ST_Simplify(geom, tolerance) SELECT ST_AsText(geom) AS original, ST_AsText(ST_Simplify(geom, 3)) AS &quot;3&quot;, ST_AsText(ST_Simplify(geom, 2.9)) AS &quot;2.9&quot; FROM ( SELECT ST_GeomFromText('LINESTRING(0 0,3 2.5,0  5)')    AS geom) AS a;
 
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;
 
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
Denormalisation Split feature types into multiple tables based on known or expected access patterns
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
 
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
Fin Workshop Evaluations are Online (url removed) This material is made available under the  Creative Commons Attribution-ShareAlike 3.0 licence http://creativecommons.org/licenses/by-sa/3.0/us/

More Related Content

What's hot

3D WebGIS using Opensource software
3D WebGIS using Opensource software3D WebGIS using Opensource software
3D WebGIS using Opensource software
Parthesh Bulbule
 
오픈소스 GIS 교육 - PostGIS
오픈소스 GIS 교육 - PostGIS오픈소스 GIS 교육 - PostGIS
오픈소스 GIS 교육 - PostGIS
JungHwan Yun
 
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
BJ Jang
 
DATABASE & WEBGIS - GIS BOOTCAMP
DATABASE & WEBGIS - GIS BOOTCAMPDATABASE & WEBGIS - GIS BOOTCAMP
DATABASE & WEBGIS - GIS BOOTCAMP
Kevin Ng'eno
 

What's hot (20)

PostGIS 시작하기
PostGIS 시작하기PostGIS 시작하기
PostGIS 시작하기
 
3D WebGIS using Opensource software
3D WebGIS using Opensource software3D WebGIS using Opensource software
3D WebGIS using Opensource software
 
공간정보거점대학 PostGIS 고급과정
공간정보거점대학 PostGIS 고급과정공간정보거점대학 PostGIS 고급과정
공간정보거점대학 PostGIS 고급과정
 
Open Source GIS 기초교육 4일차 - GeoServer 기초 2014년 7월판
Open Source GIS 기초교육 4일차 - GeoServer 기초 2014년 7월판Open Source GIS 기초교육 4일차 - GeoServer 기초 2014년 7월판
Open Source GIS 기초교육 4일차 - GeoServer 기초 2014년 7월판
 
Discover PostGIS: Add Spatial functions to PostgreSQL
Discover PostGIS: Add Spatial functions to PostgreSQLDiscover PostGIS: Add Spatial functions to PostgreSQL
Discover PostGIS: Add Spatial functions to PostgreSQL
 
LX 공간정보아카데미 PostGIS 강의자료
LX 공간정보아카데미 PostGIS 강의자료LX 공간정보아카데미 PostGIS 강의자료
LX 공간정보아카데미 PostGIS 강의자료
 
오픈소스 GIS 교육 - PostGIS
오픈소스 GIS 교육 - PostGIS오픈소스 GIS 교육 - PostGIS
오픈소스 GIS 교육 - PostGIS
 
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
[Foss4 g2013 korea]postgis와 geoserver를 이용한 대용량 공간데이터 기반 일기도 서비스 구축 사례
 
QGIS Training.pptx
QGIS Training.pptxQGIS Training.pptx
QGIS Training.pptx
 
GeoServer 기초
GeoServer 기초GeoServer 기초
GeoServer 기초
 
GeoServer, an introduction for beginners
GeoServer, an introduction for beginnersGeoServer, an introduction for beginners
GeoServer, an introduction for beginners
 
PostGIS - National Education Center for GIS: Open Source GIS
PostGIS - National Education Center for GIS: Open Source GIS PostGIS - National Education Center for GIS: Open Source GIS
PostGIS - National Education Center for GIS: Open Source GIS
 
DATABASE & WEBGIS - GIS BOOTCAMP
DATABASE & WEBGIS - GIS BOOTCAMPDATABASE & WEBGIS - GIS BOOTCAMP
DATABASE & WEBGIS - GIS BOOTCAMP
 
QGIS for Park GIS (국립공원관리공단의 QGIS 활용사례)
QGIS for Park GIS (국립공원관리공단의 QGIS 활용사례)QGIS for Park GIS (국립공원관리공단의 QGIS 활용사례)
QGIS for Park GIS (국립공원관리공단의 QGIS 활용사례)
 
Developer Intro Deck-PowerPoint - Download for Speaker Notes
Developer Intro Deck-PowerPoint - Download for Speaker NotesDeveloper Intro Deck-PowerPoint - Download for Speaker Notes
Developer Intro Deck-PowerPoint - Download for Speaker Notes
 
QGIS 활용
QGIS 활용QGIS 활용
QGIS 활용
 
Building a Spatial Database in PostgreSQL
Building a Spatial Database in PostgreSQLBuilding a Spatial Database in PostgreSQL
Building a Spatial Database in PostgreSQL
 
지리정보체계(GIS) - [2] 좌표계 이해하기
지리정보체계(GIS) - [2] 좌표계 이해하기지리정보체계(GIS) - [2] 좌표계 이해하기
지리정보체계(GIS) - [2] 좌표계 이해하기
 
오픈소스 GIS 실습 (1)
오픈소스 GIS 실습 (1)오픈소스 GIS 실습 (1)
오픈소스 GIS 실습 (1)
 
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반
공간정보아카데미 - 오픈소스GIS 분석가과정 - QGIS 공간분석일반
 

Similar to Intro To PostGIS

Scripting GeoServer with GeoScript
Scripting GeoServer with GeoScriptScripting GeoServer with GeoScript
Scripting GeoServer with GeoScript
Justin Deoliveira
 
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
djkucera
 
Stockage, manipulation et analyse de données matricielles avec PostGIS Raster
Stockage, manipulation et analyse de données matricielles avec PostGIS RasterStockage, manipulation et analyse de données matricielles avec PostGIS Raster
Stockage, manipulation et analyse de données matricielles avec PostGIS Raster
ACSG Section Montréal
 

Similar to Intro To PostGIS (20)

Sql Saturday Spatial Data Ss2008 Michael Stark Copy
Sql Saturday Spatial Data Ss2008 Michael Stark   CopySql Saturday Spatial Data Ss2008 Michael Stark   Copy
Sql Saturday Spatial Data Ss2008 Michael Stark Copy
 
GeoMesa on Apache Spark SQL with Anthony Fox
GeoMesa on Apache Spark SQL with Anthony FoxGeoMesa on Apache Spark SQL with Anthony Fox
GeoMesa on Apache Spark SQL with Anthony Fox
 
Postgres Vision 2018: PostGIS and Spatial Extensions
Postgres Vision 2018: PostGIS and Spatial ExtensionsPostgres Vision 2018: PostGIS and Spatial Extensions
Postgres Vision 2018: PostGIS and Spatial Extensions
 
SQL Geography Datatypes by Jared Nielsen and the FUZION Agency
SQL Geography Datatypes by Jared Nielsen and the FUZION AgencySQL Geography Datatypes by Jared Nielsen and the FUZION Agency
SQL Geography Datatypes by Jared Nielsen and the FUZION Agency
 
Scripting GeoServer with GeoScript
Scripting GeoServer with GeoScriptScripting GeoServer with GeoScript
Scripting GeoServer with GeoScript
 
Plone For Developers - World Plone Day, 2009
Plone For Developers - World Plone Day, 2009Plone For Developers - World Plone Day, 2009
Plone For Developers - World Plone Day, 2009
 
Spatial SQL
Spatial SQLSpatial SQL
Spatial SQL
 
GeoScript - Spatial Capabilities for Scripting Languages
GeoScript - Spatial Capabilities for Scripting LanguagesGeoScript - Spatial Capabilities for Scripting Languages
GeoScript - Spatial Capabilities for Scripting Languages
 
GeoMesa on Spark SQL: Extracting Location Intelligence from Data
GeoMesa on Spark SQL: Extracting Location Intelligence from DataGeoMesa on Spark SQL: Extracting Location Intelligence from Data
GeoMesa on Spark SQL: Extracting Location Intelligence from Data
 
2017 RM-URISA Track: Spatial SQL - The Best Kept Secret in the Geospatial World
2017 RM-URISA Track:  Spatial SQL - The Best Kept Secret in the Geospatial World2017 RM-URISA Track:  Spatial SQL - The Best Kept Secret in the Geospatial World
2017 RM-URISA Track: Spatial SQL - The Best Kept Secret in the Geospatial World
 
Python And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And PythonwinPython And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And Pythonwin
 
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator
 
2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator2017 02-07 - elastic & spark. building a search geo locator
2017 02-07 - elastic & spark. building a search geo locator
 
Handling Real-time Geostreams
Handling Real-time GeostreamsHandling Real-time Geostreams
Handling Real-time Geostreams
 
Handling Real-time Geostreams
Handling Real-time GeostreamsHandling Real-time Geostreams
Handling Real-time Geostreams
 
Lekcja stylu
Lekcja styluLekcja stylu
Lekcja stylu
 
Stockage, manipulation et analyse de données matricielles avec PostGIS Raster
Stockage, manipulation et analyse de données matricielles avec PostGIS RasterStockage, manipulation et analyse de données matricielles avec PostGIS Raster
Stockage, manipulation et analyse de données matricielles avec PostGIS Raster
 
Introduction to Oracle Spatial
Introduction to Oracle SpatialIntroduction to Oracle Spatial
Introduction to Oracle Spatial
 
Opensource gis development - part 3
Opensource gis development - part 3Opensource gis development - part 3
Opensource gis development - part 3
 

Recently uploaded

Recently uploaded (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Intro To PostGIS

  • 1. Introduction to PostGIS Presented by: Mark Leslie Mike Pumphrey Paul Ramsey
  • 2. Workshop Format Interactive C:orkshopsntro_to_postgis http://localhost/postgis/workshop Hands On All examples are executable Copy and Paste from HTML Exercises Answers will be provided (eventually) Try This sections 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 on Simple 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:orkshopsostGISoftware 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
  • 17.  
  • 18.  
  • 19.  
  • 20.  
  • 21.  
  • 22.  
  • 23.  
  • 24.  
  • 25.  
  • 26.  
  • 27.  
  • 28.  
  • 29.  
  • 30.  
  • 31.  
  • 32.  
  • 33.  
  • 34.  
  • 35.  
  • 36.  
  • 38. Creating a Spatial Database
  • 39.  
  • 40.  
  • 41.  
  • 42.  
  • 43.  
  • 44.  
  • 45.  
  • 46.  
  • 48. Loading Data Change to C:orkshopsostGISata Execute set_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[&quot;GRS 1980&quot;,6378137,298.257222101]'), ST_Length3D_Spheroid(g, 'SPHEROID[&quot;GRS 1980&quot;,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[&quot;GRS 1980&quot;,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 area FROM medford_buildings ORDER BY area DESC LIMIT 1; In square metres? SELECT ST_Area(ST_Transform(the_geom, 2839)) AS area FROM medford_buildings ORDER 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.elevation FROM medford_buildings, jacksonco_schools WHERE 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_under5years FROM jacksonco_schools, tracts, poverty WHERE tracts.ctidfp00 = geography_id2 AND ST_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_streets WHERE 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_citylimits WHERE 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_wetlands WHERE 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 distance FROM jacksonco_schools, medford_parks ORDER BY distance desc LIMIT 1; Which is closest? SELECT jacksonco_schools.name, ST_Distance(jacksonco_schools.the_geom, medford_parks.the_geom) AS distance FROM jacksonco_schools, medford_parks ORDER 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 area FROM jacksonco_schools, medford_parks WHERE ST_DWithin(jacksonco_schools.the_geom, medford_parks.the_geom, 400) GROUP BY jacksonco_schools.name ORDER 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 area FROM jacksonco_schools, medford_parks WHERE ST_DWithin(ST_Transform(jacksonco_schools.the_geom, 2839), ST_Transform(medford_parks.the_geom, 2839), 1000) GROUP BY jacksonco_schools.name ORDER 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 area FROM jacksonco_schools, medford_parks WHERE ST_DWithin(jacksonco_schools.the_geom, medford_parks.the_geom, 1000 / 0.3048) GROUP BY jacksonco_schools.name ORDER 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_total FROM jacksonco_schools s, unmarriedbytract t WHERE ST_Contains(t.the_geom, s.the_geom);
  • 167.  
  • 168. Exercises How many storm drains are within 500 feet of 'Bear Creek'?
  • 169. Exercises How many storm drains are within 500 feet of 'Bear Creek'? SELECT count(*) FROM medford_stormdrain, medford_hydro WHERE 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:rogram FilesostgreSQL.4ataostgresql.conf pgAdmin provides a Configuration 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 the write-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 the cost of 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 as random_page_cost and seq_page_cost PostgreSQL and pgAdmin provides a way to view the victorious query plan
  • 189.  
  • 190. Test Query SELECT namelow FROM 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 in c:orkshopsostGISoftwaredig Double-click on udig.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 of equality 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 a dynamic query capability 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 with distance of 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 &quot;3&quot;, ST_AsText(ST_Simplify(geom, 2.9)) AS &quot;2.9&quot; FROM ( SELECT ST_GeomFromText('LINESTRING(0 0,3 2.5,0 5)') 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 the Creative Commons Attribution-ShareAlike 3.0 licence http://creativecommons.org/licenses/by-sa/3.0/us/