This How-To will help you get started manipulating geographical data with PostGIS.
First of all, you need to have a PostgreSQL database with PostGIS running on your instance. If you are new to Dataiku you can check out the Connecting to PostgreSQL in Dataiku DSS post.
A geometry is a representation of a geographical object (possibly complex) used by PostGIS to perform fast and efficient data manipulation. Most PostGIS functions take geometries as arguments, so we need to understand how to convert other coordinates into geometries.
The most common geographical data are points. So, how do we convert a standard (longitude,latitude) tuple to a PostGIS geometry? With the ST_MakePoint function. It takes the longitude, latitude, and altitude and returns a geometry of type
Here is an example of such a request:
In order to use your new geometries with other PostGIS functions, you need to specify the coordinate system (SRID) of your points with the ST_SetSRID function. The most widely used system is SRID=4326; that is, GPS coordinates). If you have no idea where your data comes from, it’s probably this one.
So our request becomes:
Sometimes you may want to convert your data to a specific coordinate system. It is possible with the ST_Transform function, which moves the coordinates of a geometry from its current system to another one.
For example, if we want to project our data into the French ‘Lambert Nord standard’ system (SRID=27561) we can modify our request like this:
If you want to convert from your geometry to the classic tuple (longitude,latitude), you can do this by using the ST_AsText function, which takes a geometry and returns a text (known as “WKT” format).
Once you know how to make points it is simple to build lines. You just have to use the ST_MakeLine function, which takes two points (see previous section) and builds the line between them.
You can also give an array of points and the function will draw the line which interpolates those points.
And then there are several interesting functions to characterize this line. You can:
The last main geometry you have to know is the polygon. As you can guess, it delineates an area. There are many ways to build a polygon from points, lines, other polygons… here we will cover two methods.
The first one is the simplest; it creates a polygon from a closed line. This is the ST_MakePolygon function, which draws lines from point to point, with the first and last points the same.
Here is an example:
The other method is more complicated, but also useful. The aim is to build the smallest convex polygon containing a collection of points. In order to do that, you first need to build a geometry from a collection of points with the function ST_Collect and then use the ST_ConvexHull function to create the polygon.
Here is an example:
Now that you know how to make geomtries, here is a non-exhaustive list of useful functions you can use to manipulate them: