+1 (726) 227-3497

Geospatial Queries in Amazon Redshift: GEOMETRY, Shapefile Loads and Spatial Joins That Scale

Most Redshift tutorials stop at orders, events and clickstream. But a lot of warehouses also hold location data: store and warehouse coordinates, delivery zones, service territories, device pings. Redshift has native spatial types and SQL functions for this, so "which customers are inside which zone" does not need a round trip to PostGIS or a client-side script. This guide covers the practical path: types, loading, the core queries, and how to keep spatial joins from turning into a full cross join.

Check the current Amazon Redshift documentation for the exact list of supported spatial functions and limits before you build on any of this. Coverage has expanded over time.

GEOMETRY vs GEOGRAPHY

  • GEOMETRY is planar. Coordinates are x/y on a flat plane and distances come back in the units of the coordinate system. It has the broadest function support.
  • GEOGRAPHY is for longitude/latitude on the earth's surface (SRID 4326). Function support is narrower than GEOMETRY.

A pragmatic default: store GEOMETRY with SRID 4326 for lon/lat points, and use the spherical distance function when you need meters. Reach for a projected SRID only when you need precise planar work in one region.

CREATE TABLE dim_store (
    store_id   INT,
    store_name VARCHAR(100),
    lon        DOUBLE PRECISION,
    lat        DOUBLE PRECISION,
    location   GEOMETRY
)
DISTSTYLE ALL
SORTKEY (store_id);

INSERT INTO dim_store
SELECT store_id, store_name, lon, lat,
       ST_SetSRID(ST_Point(lon, lat), 4326)
FROM   stg_store;

Note the argument order: ST_Point(x, y) is longitude first, then latitude. Swapped coordinates are the most common spatial bug, and the points still load without complaint.

Loading polygons

Zones and territories usually arrive as WKT text, GeoJSON or shapefiles. WKT converts directly:

CREATE TABLE dim_zone (
    zone_id INT,
    zone_name VARCHAR(100),
    boundary GEOMETRY
);

INSERT INTO dim_zone
SELECT zone_id, zone_name, ST_GeomFromText(wkt, 4326)
FROM   stg_zone;

For shapefiles, COPY supports a shapefile format that reads from S3. The .shp, .shx and .dbf files must sit together under the same prefix:

COPY dim_zone
FROM 's3://my-bucket/zones/zones.shp'
IAM_ROLE default
FORMAT SHAPEFILE;

The first geometry column of the target table receives the shape, and later columns map to the attribute data in order. Run a validity check after load:

SELECT zone_id FROM dim_zone WHERE NOT ST_IsValid(boundary);

Invalid polygons (self-intersections, unclosed rings) give wrong or failing results in joins, so fix them at load time rather than in every query.

The core queries

Which zone is each customer in?

SELECT c.customer_id, z.zone_name
FROM   dim_customer c
JOIN   dim_zone z
  ON   ST_Contains(z.boundary, c.location);

Stores within 5 km of a point, using spherical distance in meters:

SELECT store_id, store_name,
       ST_DistanceSphere(location, ST_SetSRID(ST_Point(-122.4194, 37.7749), 4326)) AS meters
FROM   dim_store
WHERE  ST_DistanceSphere(location, ST_SetSRID(ST_Point(-122.4194, 37.7749), 4326)) < 5000
ORDER  BY meters;

Nearest store per customer with a window function:

SELECT customer_id, store_id, meters
FROM (
  SELECT c.customer_id, s.store_id,
         ST_DistanceSphere(c.location, s.location) AS meters,
         ROW_NUMBER() OVER (PARTITION BY c.customer_id
                            ORDER BY ST_DistanceSphere(c.location, s.location)) AS rn
  FROM dim_customer c
  CROSS JOIN dim_store s
) t
WHERE rn = 1;

That last query is correct but is a cross join: customers × stores. Fine for 50,000 customers and 200 stores, painful at 50 million customers. See below.

Keeping spatial joins cheap

Redshift has no spatial index. A spatial predicate in a join condition is evaluated pair by pair, so the work is proportional to the pairs you let through. The fixes are ordinary warehouse techniques:

  1. Prefilter with plain numbers. Store lon/lat as separate numeric columns (as above) and add a cheap bounding-box condition that Redshift can evaluate with zone maps and ordinary comparisons, before the expensive predicate:
SELECT c.customer_id, z.zone_id
FROM   dim_customer c
JOIN   dim_zone z
  ON   c.lon BETWEEN z.min_lon AND z.max_lon
 AND   c.lat BETWEEN z.min_lat AND z.max_lat
 AND   ST_Contains(z.boundary, c.location);

Precompute min_lon, max_lon, min_lat, max_lat per zone once, for example with ST_XMin, ST_XMax, ST_YMin and ST_YMax.

  1. Use a grid or geohash key. Assign each point and each polygon to coarse grid cells, join on the cell id (an equality join Redshift handles well), then apply ST_Contains to the survivors. A polygon that spans several cells gets one row per cell.

  2. Distribute the small side. Zones and stores are usually small, so DISTSTYLE ALL avoids redistribution. Keep the big fact table on its normal key.

  3. Materialize the result. A customer's zone changes rarely. Compute it once per load into a column or a mapping table instead of re-running the spatial join in every dashboard query. For events, resolve the zone at ELT time and store zone_id on the fact row.

  4. Check the plan. Run EXPLAIN and look for a nested loop join. That is expected when the only join condition is a spatial predicate, and it is the signal to add steps 1 or 2.

Joining to the rest of your model

Once zone_id is a plain integer on your facts, the spatial work is done and everything downstream is a normal star-schema join. This is the real payoff: BI tools such as QuickSight, Tableau or Power BI do not need to understand geometry. They group by zone_name.

If a tool needs to read the geometry itself, export it as text:

SELECT zone_id, ST_AsText(boundary) AS wkt FROM dim_zone;

Large polygons make large rows, so do not select the boundary column in queries that do not need it.

Gotchas

  • Swapped lon/lat. Check a few known points with ST_X and ST_Y after loading.
  • Mixed SRIDs. Combining geometries with different SRIDs raises an error. Set the SRID explicitly on both sides at load time.
  • Degrees are not meters. Planar distance on SRID 4326 geometry returns degrees. Use ST_DistanceSphere or a projected SRID for real distances.
  • Invalid shapes. Validate with ST_IsValid at load and quarantine the failures.
  • Row size. Very detailed boundaries, such as coastlines, can be large. Simplify them with ST_Simplify where the precision is not needed.

When to get help

Spatial workloads show where a data model was built for reports and not for location questions. If you are planning a territory, logistics or store-network warehouse on Redshift, the usual decisions are the grid strategy, where to resolve zones in the pipeline, and how much geometry should reach the BI layer. RougeWarehouse's data modeling and performance consultants can review that design before it hardens. Get in touch to scope it.