Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Created May 1, 2025 17:57
Show Gist options
  • Save akhenakh/86e65a1b5a967d6dfafc0a103fffba3b to your computer and use it in GitHub Desktop.
Save akhenakh/86e65a1b5a967d6dfafc0a103fffba3b to your computer and use it in GitHub Desktop.
Using Duckdb to query point in polygons in an efficient manner
-- source https://www.census.gov/geographies/mapping-files/time-series/geo/carto-boundary-file.html
-- https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_state_5m.zip
LOAD spatial;
LOAD geography;
CREATE TABLE wkbstates AS
SELECT
name,
ST_AsWKB(geom) as geom_wkb -- Convert GEOMETRY to WKB_BLOB
FROM ST_Read('us-states-census.geojson'); -- Read the GeoJSON file
CREATE OR REPLACE TABLE states AS
SELECT
name,
s2_prepare( -- Prepare for faster queries
s2_geogfromwkb(geom_wkb) -- Convert WKB (Lon/Lat assumed) to GEOGRAPHY
) AS geog
FROM wkbstates;
SELECT
states.name
FROM states
WHERE s2_contains(states.geog, 'POINT (-122.33 47.61)'::GEOGRAPHY);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment