duckdb-geography: Global vector data in DuckDB
Dewey Dunnington, Wherobots Inc.
duckdb-geography
In a nutshell:
import duckdb
con = duckdb.connect ()
con.install_extension("geography" , repository= "community" )
con.load_extension("geography" )
con.table_function("s2_data_cities" ).limit(3 )
┌──────────────┬────────────┬──────────────────────────────────────────────┐
│ name │ population │ geog │
│ varchar │ int32 │ geography │
├──────────────┼────────────┼──────────────────────────────────────────────┤
│ Vatican City │ 832 │ POINT (12.4533865 41.90328219999999) │
│ San Marino │ 29000 │ POINT (12.441770200000002 43.93609579999999) │
│ Vaduz │ 5342 │ POINT (9.51666947 47.1337238) │
└──────────────┴────────────┴──────────────────────────────────────────────┘
Data Types
Examples
The Future
Data types: Geography
A Geography is a Geometry whose edges follow a the shortest distance on the Earth rather than the shortest distance in Cartesian/planar space
If you want to represent something like Fiji, Russia, or Antarctica without splitting it into pieces, you need Geography!
Data types: Geography
Spherely array:
Order is kept
In memory data structures
Requires explicit parallelization
DuckDB Geography:
Order is sometimes kept
Serialized data structures (can be slower)
Automatic parallelization
Data types: Geography
…to Iceberg, Parquet, and Apache Sedona (and already exists in Python, R, Snowflake, PostGIS, BigQuery, SQL Server, and elsewhere)
Data types: S2 Cell
con.sql("""
SELECT s2_cellfromlonlat(7.64, 47.53).s2_cell_parent(level)
FROM (VALUES (5), (4), (3), (2), (1), (0)) levels(level)
""" )
┌─────────────────────────────────────────────────────────┐
│ s2_cell_parent(s2_cellfromlonlat(7.64, 47.53), "level") │
│ s2_cell │
├─────────────────────────────────────────────────────────┤
│ 2/03302 │
│ 2/0330 │
│ 2/033 │
│ 2/03 │
│ 2/0 │
│ 2/ │
└─────────────────────────────────────────────────────────┘
Data types: S2 Cell
S2 Cells are represented by uint64_t and have an important property: containment can be calculated using a simple comparison
con.sql("""
SELECT c, s2_cell_range_min(c), s2_cell_range_max(c)
FROM (VALUES ('2/0330'::S2_CELL)) cells(c)
""" )
┌─────────┬──────────────────────────────────┬──────────────────────────────────┐
│ c │ s2_cell_range_min(c) │ s2_cell_range_max(c) │
│ s2_cell │ s2_cell │ s2_cell │
├─────────┼──────────────────────────────────┼──────────────────────────────────┤
│ 2/0330 │ 2/033000000000000000000000000000 │ 2/033033333333333333333333333333 │
└─────────┴──────────────────────────────────┴──────────────────────────────────┘
Data types: S2 Cell
Cells are implicitly castable to Geography:
con.sql("SELECT '2/0030'::S2_CELL::GEOGRAPHY AS geog" )
┌──────────────────────────────────────────────────────────────────────────────┐
│ geog │
│ geography │
├──────────────────────────────────────────────────────────────────────────────┤
│ POLYGON ((56.88865803962798 44.96817331739243, 63.57747534364858 46.882504… │
└──────────────────────────────────────────────────────────────────────────────┘
Data types: S2 Cell Center
(
con
.table_function("s2_data_cities" )
.select("geog" )
.limit(5 )
)
┌────────────────────────────────────────────────┐
│ geog │
│ geography │
├────────────────────────────────────────────────┤
│ POINT (12.4533865 41.90328219999999) │
│ POINT (12.441770200000002 43.93609579999999) │
│ POINT (9.51666947 47.1337238) │
│ POINT (31.199997100000004 -26.466667500000003) │
│ POINT (6.13000281 49.61166039999999) │
└────────────────────────────────────────────────┘
Data types: S2 Cell Center
(
con
.table_function("s2_data_cities" )
.select("geog::S2_CELL_CENTER AS cell" )
.limit(5 )
)
┌──────────────────────────────────┐
│ cell │
│ s2_cell_center │
├──────────────────────────────────┤
│ 0/212113230003023131001102313200 │
│ 0/212112131211123020010233101310 │
│ 2/033031212023000232111020023022 │
│ 0/331313212213231033112021020221 │
│ 2/033022221321121102131101113231 │
└──────────────────────────────────┘
Data types: S2 Cell Center
(
con
.table_function("s2_data_cities" )
.select("geog::S2_CELL_CENTER::GEOGRAPHY AS cell" )
.limit(5 )
)
┌───────────────────────────────────────────────┐
│ cell │
│ geography │
├───────────────────────────────────────────────┤
│ POINT (12.453386500260923 41.903282180235685) │
│ POINT (12.441770226609517 43.93609579566802) │
│ POINT (9.51666945984589 47.13372383059051) │
│ POINT (31.19999705922266 -26.466667544230447) │
│ POINT (6.130002858834869 49.61166041609344) │
└───────────────────────────────────────────────┘
Data types: S2 Cell Union
con.sql("SELECT s2_data_country('Switzerland').s2_covering()" )
┌────────────────────────────────────────────────────────────────────────────────────┐
│ s2_covering(s2_data_country('Switzerland')) │
│ s2_cell_union │
├────────────────────────────────────────────────────────────────────────────────────┤
│ [2/033001, 2/033002, 2/033010, 2/033012, 2/033013, 2/033020, 2/03302100, 2/033031] │
└────────────────────────────────────────────────────────────────────────────────────┘
Data types: S2 Cell Union
con.sql("SELECT s2_data_country('Switzerland').s2_covering()" )
Data types: S2 Cell Union
Cells Unions are implicitly castable to Geography:
con.sql("""
SELECT s2_data_country('Switzerland').s2_covering()::GEOGRAPHY
""" )
┌──────────────────────────────────────────────────────────────────────────────┐
│ CAST(s2_covering(s2_data_country('Switzerland')) AS GEOGRAPHY) │
│ geography │
├──────────────────────────────────────────────────────────────────────────────┤
│ POLYGON ((8.851494069127982 48.37854425883403, 7.289681472358652 48.488487… │
└──────────────────────────────────────────────────────────────────────────────┘
Paralellizing a trivial workflow
Partitioning
Joining
Hands on: Parallelizing a workflow
con.sql("""
SELECT s2_bounds_box_agg(geog) FROM s2_data_countries()
WHERE continent IN ('Oceania', 'Asia', 'Antarctica')
GROUP BY continent
""" )
┌───────────────────────────────────────────────────────────────────────────────────────────────────┐
│ s2_bounds_box_agg(geog) │
│ s2_box │
├───────────────────────────────────────────────────────────────────────────────────────────────────┤
│ {'xmin': 26.043351, 'ymin': -10.359987000000027, 'xmax': 145.543137, 'ymax': 55.38525000000003} │
│ {'xmin': -180.0, 'ymin': -90.0, 'xmax': 180.0, 'ymax': -63.270660999999976} │
│ {'xmin': 113.338953, 'ymin': -46.64123500000003, 'xmax': -179.79332, 'ymax': -2.5000019999999745} │
└───────────────────────────────────────────────────────────────────────────────────────────────────┘
Hands on: Parallelizing a workflow
Most useful for tasks that won’t benefit from a spatial index and benefit from automagic global handling:
s2_bounds_box() and s2_bounds_box_agg()
s2_area(), s2_distance(), s2_perimeter()
s2_covering()
::S2_CELL_CENTER
For other tasks, consider DuckDB Spatial (if you don’t need an index to assist with a join), PostGIS, or Apache Sedona (if you do).
Hands on: Partitioning
Take a porentially larger-than-memory dataset and split it into chunks based on location
con.load_extension("spatial" )
con.sql("""
SELECT
geometry.st_aswkb()
.s2_arbitrarycellfromwkb().s2_cell_parent(3)
.s2_cell_token() AS cell,
*
FROM "microsoft-buildings_point_geo.parquet"
""" ).write_parquet(
"microsoft-buildings-partitioned" ,
partition_by= ["cell" ],
overwrite= True
)
Hands on: Partitioning
ls -lh microsoft-buildings-partitioned/** /* .parquet
-rw-r--r--@ 1 dewey staff 20M Jun 24 13:32 microsoft-buildings-partitioned/cell=4cc/data_0.parquet
-rw-r--r--@ 1 dewey staff 9.1M Jun 24 13:32 microsoft-buildings-partitioned/cell=4d4/data_0.parquet
-rw-r--r--@ 1 dewey staff 40M Jun 24 13:32 microsoft-buildings-partitioned/cell=52c/data_0.parquet
-rw-r--r--@ 1 dewey staff 23M Jun 24 13:32 microsoft-buildings-partitioned/cell=534/data_0.parquet
-rw-r--r--@ 1 dewey staff 87M Jun 24 13:32 microsoft-buildings-partitioned/cell=54c/data_0.parquet
-rw-r--r--@ 1 dewey staff 189M Jun 24 13:32 microsoft-buildings-partitioned/cell=80c/data_0.parquet
-rw-r--r--@ 1 dewey staff 15K Jun 24 13:32 microsoft-buildings-partitioned/cell=814/data_0.parquet
-rw-r--r--@ 1 dewey staff 191M Jun 24 13:32 microsoft-buildings-partitioned/cell=864/data_0.parquet
-rw-r--r--@ 1 dewey staff 24M Jun 24 13:32 microsoft-buildings-partitioned/cell=86c/data_0.parquet
-rw-r--r--@ 1 dewey staff 102M Jun 24 13:32 microsoft-buildings-partitioned/cell=874/data_0.parquet
-rw-r--r--@ 1 dewey staff 207M Jun 24 13:32 microsoft-buildings-partitioned/cell=87c/data_0.parquet
-rw-r--r--@ 1 dewey staff 505M Jun 24 13:32 microsoft-buildings-partitioned/cell=884/data_0.parquet
-rw-r--r--@ 1 dewey staff 228M Jun 24 13:32 microsoft-buildings-partitioned/cell=88c/data_0.parquet
-rw-r--r--@ 1 dewey staff 2.9M Jun 24 13:32 microsoft-buildings-partitioned/cell=894/data_0.parquet
-rw-r--r--@ 1 dewey staff 331M Jun 24 13:32 microsoft-buildings-partitioned/cell=89c/data_0.parquet
Hands on: Partitioning
Hands on: Joining
Let’s count these by zipcode using geopandas?
import geopandas
import pandas as pd
zipcodes_df = geopandas.read_parquet("us-zip-codes.parquet" )
buildings_df = geopandas.read_parquet("microsoft-buildings_point_geo.parquet" )
sindex = buildings_df.geometry.sindex
result = sindex.query(zipcodes_df.geometry, predicate= "contains" )
counts = pd.Series(result[0 ]).value_counts(sort= False )
(You might run out of memory)
Hands on: Joining
Let’s count these by by zipcode using PostGIS?
SELECT zipcodes.zipcode, count (* ) as numpoints
FROM zipcodes
JOIN buildings ON ST_Contains(zipcodes.geom, buildings.geom)
GROUP BY zipcodes.zipcode
(Getting the data into the database takes longer than the computation)
Hands on: Joining
Let’s count these by zipcode using DuckDB spatial?
WITH
buildings AS (SELECT * FROM "microsoft-buildings_point_geo.parquet" ),
zipcodes AS (SELECT * FROM "us-zip-codes.parquet" )
SELECT zipcodes.zipcode, count (* ) as numpoints
FROM zipcodes
JOIN buildings ON ST_Contains(zipcodes.geom, buildings.geometry)
GROUP BY zipcodes.zipcode
(DuckDB can’t use an index for a join yet!)
Hands on: Joining
Let’s count these by zipcode using WherobotsDB!
config = SedonaContext.builder().getOrCreate()
sedona = SedonaContext.create(config)
sedona.read.format ("shapefile" ).load("us-zip-codes.parquet" )\
.createOrReplaceTempView("zipcodes" )
sedona.read.format ("geoparquet" ).load("microsoft-buildings_point_geo.parquet" )\
.createOrReplaceTempView("buildings" )
sedona.sql("""
SELECT zipcodes.zipcode as zipcode, count(*) as numpoints
FROM zipcodes
JOIN buildings ON ST_Contains(zipcodes.geometry, buildings.geom)
GROUP BY zipcode""" )
Hands on: Joining
Let’s count these by zipcode using DuckDB-geography!
con.sql("""
SELECT
zipcode,
geom.st_aswkb().s2_geogfromwkb() AS geog,
geog.s2_covering() AS covering
FROM "us-zip-codes.parquet"
""" ).to_view("zipcodes_original" )
…by using S2 cells as something that DuckDB knows how to optimize the join for.
Hands on: Joining
con.sql("""
SELECT
zipcode,
geom.st_aswkb().s2_geogfromwkb().s2_prepare() AS geog,
geog.s2_covering() AS covering
FROM "us-zip-codes.parquet"
""" ).to_view("zipcodes_original" )
┌─────────┬──────────────────────┬────────────────────────────────────────────────────────┐
│ zipcode │ geog │ covering │
│ varchar │ geography │ s2_cell_union │
├─────────┼──────────────────────┼────────────────────────────────────────────────────────┤
│ 15301 │ <S2ShapeIndex 9666… │ [4/1001220212, 4/1001220221, 4/100122022211, 4/10012… │
└─────────┴──────────────────────┴────────────────────────────────────────────────────────┘
Hands on: Joining
con.sql("""
SELECT
unnest(covering) as cell,
zipcode,
geog,
cell.s2_cell_range_min() AS cell_min,
cell.s2_cell_range_max() AS cell_max
FROM zipcodes_original""" ).to_table("zipcodes" )
┌──────────────┬─────────┬──────────────────────┬──────────────────────┬────────────────────────────┐
│ cell │ zipcode │ geog │ cell_min │ cell_max │
│ s2_cell │ varchar │ geography │ s2_cell │ s2_cell │
├──────────────┼─────────┼──────────────────────┼──────────────────────┼────────────────────────────┤
│ 4/1001220212 │ 15301 │ <S2ShapeIndex 9666… │ 4/1001220212000000… │ 4/1001220212333333333333… │
└──────────────┴─────────┴──────────────────────┴──────────────────────┴────────────────────────────┘
Hands on: Joining
con.sql("""
SELECT geometry.st_aswkb().s2_cellfromwkb() as cell
FROM "microsoft-buildings_point_geo.parquet"
""" ).to_table("buildings" )
┌──────────────────────────────────┐
│ cell │
│ s2_cell_center │
├──────────────────────────────────┤
│ 4/030313311232030030032122121030 │
│ 4/030313311232031331311131310220 │
│ 4/030313311232031322310022111120 │
└──────────────────────────────────┘
Hands on: Joining
con.sql("""
SELECT zipcodes.zipcode, count(*) as numpoints
FROM buildings
LEFT JOIN zipcodes ON
zipcodes.cell_min <= buildings.cell
AND zipcodes.cell_max >= buildings.cell
WHERE s2_contains(zipcodes.geog, buildings.cell)
GROUP BY zipcode
""" )
The Future
Better integration with spatial (e.g., geog::GEOMETRY)
Aggregators
Import/Export/Fix spherical geometry
Something else based on user experience?
duckdb-geography
Install from Python:
import duckdb
duckdb.install_extension("geography" , repository= "community" )
Install from SQL:
INSTALL geography FROM community;