DuckDB Extension
A5 Geospatial Index
Group geographic points into A5 pentagonal cells in DuckDB. Use cell IDs to count points by area, join datasets, or roll up to a coarser grid.
On this page
Sample data for the examples
Each browser example starts with these sample tables; sample files are shared across examples on this page. Run this setup first when trying the examples in your own DuckDB session.
-- Test fixtures for a5 cookbook / quickstart / technical-details snippets.
-- Provides small deterministic lat/lng tables so the snippets that
-- aggregate or join real geographic data can parse and execute.
--
-- Idempotent: every CREATE uses OR REPLACE so re-running the harness on
-- the same connection is safe.
-- ---------------------------------------------------------------------
-- Base point set: 20 well-known city coordinates. Used as a building
-- block for every other table so all fixtures are mutually consistent.
-- ---------------------------------------------------------------------
CREATE OR REPLACE TEMP TABLE _a5_cities AS
SELECT * FROM (VALUES
(-74.0060, 40.7128, 'New York'),
(-73.9352, 40.7306, 'Brooklyn'),
(-73.9857, 40.7484, 'Midtown'),
(-74.0445, 40.6892, 'Liberty'),
(-73.7781, 40.6413, 'JFK'),
(-118.2437, 34.0522, 'Los Angeles'),
(-118.4085, 33.9416, 'LAX'),
(-122.4194, 37.7749, 'San Francisco'),
(-122.2711, 37.8044, 'Oakland'),
(-122.0838, 37.3861, 'Mountain View'),
( -87.6298, 41.8781, 'Chicago'),
( -71.0589, 42.3601, 'Boston'),
( -77.0369, 38.9072, 'Washington DC'),
( -80.1918, 25.7617, 'Miami'),
( -95.3698, 29.7604, 'Houston'),
( -3.7037, 40.4168, 'Madrid'),
( 2.3522, 48.8566, 'Paris'),
( -0.1276, 51.5074, 'London'),
( 139.6503, 35.6762, 'Tokyo'),
( 151.2093,-33.8688, 'Sydney')
) AS t(lon, lat, name);
-- ---------------------------------------------------------------------
-- `points` β referenced by metadata.json:quickStart.
-- Columns: longitude, latitude.
-- ---------------------------------------------------------------------
CREATE OR REPLACE TABLE points AS
SELECT lon AS longitude, lat AS latitude
FROM _a5_cities;
-- ---------------------------------------------------------------------
-- `pickups` β referenced by technical-details.mdx "What you can do".
-- Columns: longitude, latitude. 50 deterministic rows generated by
-- duplicating the city set with small lat/lng perturbations so GROUP BY
-- yields multiple rows per cell at typical resolutions.
-- ---------------------------------------------------------------------
CREATE OR REPLACE TABLE pickups AS
SELECT
lon + (i * 0.0003) AS longitude,
lat + (i * 0.0002) AS latitude
FROM _a5_cities,
generate_series(0, 4) AS g(i);
-- ---------------------------------------------------------------------
-- `transactions` β referenced by cookbook.mdx aggregate + spatial-join.
-- Columns: longitude, latitude, amount, cell_15.
-- cell_15 is pre-computed at resolution 15 so the join example can
-- match the `events` CTE directly.
-- ---------------------------------------------------------------------
CREATE OR REPLACE TABLE transactions AS
SELECT
lon + (i * 0.0001) AS longitude,
lat + (i * 0.0001) AS latitude,
(10.0 + i * 1.5) AS amount,
a5_lonlat_to_cell(lon + (i * 0.0001),
lat + (i * 0.0001), 15) AS cell_15
FROM _a5_cities,
generate_series(0, 2) AS g(i);
-- ---------------------------------------------------------------------
-- `raw_points` β referenced by cookbook.mdx + technical-details.mdx
-- "roll up to a coarser resolution" examples.
-- Columns: lon, lat.
-- ---------------------------------------------------------------------
CREATE OR REPLACE TABLE raw_points AS
SELECT lon, lat FROM _a5_cities;
-- ---------------------------------------------------------------------
-- `indexed` β referenced by cookbook.mdx + technical-details.mdx
-- "roll up" snippets. Examples that rebuild this table use CREATE OR REPLACE.
-- Columns: lon, lat, cell_15.
-- ---------------------------------------------------------------------
CREATE OR REPLACE TABLE indexed AS
SELECT lon, lat, a5_lonlat_to_cell(lon, lat, 15) AS cell_15
FROM _a5_cities;
-- ---------------------------------------------------------------------
-- `event_points` β referenced by cookbook.mdx spatial-join example.
-- Columns: lon, lat.
-- ---------------------------------------------------------------------
CREATE OR REPLACE TABLE event_points AS
SELECT lon, lat FROM _a5_cities;
-- ---------------------------------------------------------------------
-- `zone_centroids` β referenced by cookbook.mdx spatial-join example.
-- Columns: lon, lat, zone_name.
-- ---------------------------------------------------------------------
CREATE OR REPLACE TABLE zone_centroids AS
SELECT lon, lat, name AS zone_name FROM _a5_cities;
Group geographic points into equal-area cells
A5 divides the globe into a hierarchy of pentagonal cells. The extension converts longitude and latitude into a cell ID, so locations can be grouped and joined using an integer instead of a pair of coordinates.
Use it to count events by area, compare geographic densities, or summarize a detailed grid at a coarser resolution. Cells at the same resolution have equal area. You can turn a cell back into a polygon when you need to draw it on a map.
Example
Put two nearby points in grid cells
The sample includes two New York coordinates. A5 takes longitude first, then latitude; resolution controls cell size.
Tested with DuckDB 1.5.6. Browser examples use Haybarn-Wasm 2.0.0-rc12.
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://duckdb-extensions.query.farm';
INSTALL a5 FROM query_farm;
LOAD a5 FROM query_farm;
WITH points(longitude, latitude) AS (
VALUES (-74.0060, 40.7128), (-74.0061, 40.7129)
)
SELECT a5_lonlat_to_cell(longitude, latitude, 10) AS cell_id,
count(*) AS point_count
FROM points
GROUP BY cell_id
ORDER BY cell_id;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL a5 FROM query_farm;
LOAD a5 FROM query_farm;
WITH points(longitude, latitude) AS (
VALUES (-74.0060, 40.7128), (-74.0061, 40.7129)
)
SELECT a5_lonlat_to_cell(longitude, latitude, 10) AS cell_id,
count(*) AS point_count
FROM points
GROUP BY cell_id
ORDER BY cell_id;
INSTALL a5 FROM community;
LOAD a5;
WITH points(longitude, latitude) AS (
VALUES (-74.0060, 40.7128), (-74.0061, 40.7129)
)
SELECT a5_lonlat_to_cell(longitude, latitude, 10) AS cell_id,
count(*) AS point_count
FROM points
GROUP BY cell_id
ORDER BY cell_id;
These points fall in one cell, giving a point count of 2. The numeric cell ID differs between A5 builds: check the migration notes before combining stored IDs. Cell membership is a grid approximation; use an exact geometry predicate when a boundary matters.
Common tasks
Deep Dive
Technical Details
DuckDB β A5 Pentagonal Grid
A pentagon-based discrete global grid system β an alternative to H3 and S2 with equal-area cells at every resolution.
What you can do with one query
Turn a table of (longitude, latitude) points into a heatmap-style aggregation in one statement:
SELECT a5_lonlat_to_cell(longitude, latitude, 10) AS cell_id, COUNT(*) AS point_countFROM pickupsGROUP BY cell_idORDER BY point_count DESC;a5_lonlat_to_cell returns a UBIGINT you can GROUP BY, JOIN, or index β the same role H3 / S2 cell IDs play in those systems. Because A5 cells are equal-area at each resolution, the resulting counts are directly comparable across latitudes without per-cell normalization.
A5 is a newer discrete global grid system. Its specification and reference library at github.com/felixpalmer/a5 are stable, but the surrounding ecosystem is much smaller than H3βs β fewer first-party bindings (Postgres, BigQuery, Spark), fewer Stack Overflow answers, fewer existing pipelines that emit A5 IDs.
Reach for A5 specifically when uniform cell area matters: cross-latitude density comparisons, equal-area sampling, anything where H3βs hex-area variation (it swings by roughly 2Γ across the globe, in a smooth soccer-ball-like pattern, not just near the poles) is a problem. For βthe broadest tool supportβ or βmatching what the rest of my stack uses,β H3 is still the conservative pick. The upstream A5 vs H3 page walks through the trade in detail.
This extension is built on A5 1.0, a breaking release. The same cell now has a different ID at resolution 2 and finer β and old IDs are still well-formed, so they silently name different cells. Convert stored IDs once with a5_migrate. Coverings (a5_compact, a5_grid_disk, a5_spherical_cap, polygon a5_geometry_to_cells, β¦) now end in a compaction marker, and a5_uncompact no longer takes a resolution. The upgrade guide has the full checklist.
A5 vs H3 vs S2 at a glance
| Property | A5 (this extension) | H3 | S2 |
|---|---|---|---|
| Cell shape | Pentagons throughout | Hexagons (+ 12 pentagon exceptions) | Curvilinear quadrilaterals |
| Equal area | Yes, at every resolution | Approximate; varies ~2Γ across the globe | Approximate; varies with face |
| Edge neighbors | 5 | 6 (mostly) | 4 |
| ID type | UBIGINT |
UBIGINT |
UBIGINT |
| Resolution levels | 31 (0β30) | 16 (0β15) | 31 (0β30) |
| DuckDB extension here | Yes | Via h3 community extension |
No first-party DuckDB extension as of writing |
| Ecosystem | Newer; small but growing | Large (Uber, Postgres, BigQuery, Snowflake, β¦) | Large inside Google products |
If youβre already on H3 and its hex-area variation isnβt biting you, thereβs no reason to switch. If youβre starting fresh and equal-area cells matter, A5 is a good pick.
Resolution guide
Pick the coarsest resolution that still distinguishes the phenomena youβre measuring β each finer level is roughly a 4Γ row count after GROUP BY.
| Resolution | Cell area (approx) | Typical use |
|---|---|---|
| 0β5 | 42.5M kmΒ² β 33k kmΒ² | Continental / country-scale rollup |
| 6β10 | 8.3k kmΒ² β 32 kmΒ² | Regional / metro-scale analysis |
| 11β15 | 8.1 kmΒ² β 3.2 hectares | City / district analysis |
| 16β20 | 7,900 mΒ² β 31 mΒ² | Neighborhood / building analysis |
| 21β25 | 7.7 mΒ² β 300 cmΒ² | Room / vehicle scale |
| 26β30 | 75 cmΒ² β 0.3 cmΒ² | Sub-meter precision |
a5_cell_area returns the exact equal-area size for any resolution; a5_cell_edge_length_avg returns the average edge length in meters (individual edges vary from it by roughly Β±10%); a5_get_num_cells returns the global cell count.
Hierarchy and compaction
A5βs 31-level hierarchy means one encode at the finest resolution youβll need supports every coarser zoom:
-- Encode once at the finest resolutionCREATE OR REPLACE TABLE indexed ASSELECT *, a5_lonlat_to_cell(lon, lat, 15) AS cell_15FROM raw_points;
-- Roll up to a coarser view without re-reading raw pointsSELECT a5_cell_to_parent(cell_15, 10) AS cell_10, COUNT(*) AS nFROM indexedGROUP BY cell_10;a5_cell_to_parent walks any cell to a coarser ancestor (omit the resolution for the immediate parent; -1 gives the world cell); a5_cell_to_children goes the other way.
Those follow the cell-ID hierarchy, and A5 cells donβt nest exactly across resolutions β a cellβs parent need not contain it. The geometric counterparts are a5_cell_to_supercell, the coarser cell that contains the cellβs center, and a5_cell_to_subcells, the finer cells whose centers lie inside it. Roll up by supercell when the coarse buckets must respect real geography; the parent is a cheaper pure-integer walk thatβs fine when the buckets only need to be consistent.
Coverings and set operations
A region is a list of cells, and A5 1.0 gives that list a canonical shape: a covering. Its cells are compacted (every complete group of siblings replaced by its parent, recursively), sorted in curve order, and followed by one compaction marker β a UBIGINT that is not a cell and records the resolution the cells stand for. a5_compact, a5_grid_disk, a5_grid_disk_vertex, a5_spherical_cap, a5_cell_to_subcells, the set operations below, and polygon results of a5_geometry_to_cells all return coverings.
SELECT a5_grid_disk(a5_lonlat_to_cell(-74.0060, 40.7128, 15), 1) AS covering;-- [2760557102958116864, 2760559170447998976, 2760559181722288128, 17298044693753364544]-- three compacted cells, then the marker (resolution 15)Because the marker isnβt a cell, expand a covering before treating its elements as cells: a5_uncompact(cells) expands to the coveringβs own resolution and drops the marker, and a5_is_compaction_marker filters it out if you want the compacted cells themselves. Most of the time you donβt need to expand at all β every function that takes a list of cells accepts a covering (or a plain list, whose resolution is that of its finest cell):
a5_count,a5_area,a5_covering_resolutionβ size, square meters, and resolution of a region.a5_union,a5_intersect,a5_differenceβ combine two regions into a new covering.a5_overlaps,a5_containsβ region-vs-region and region-vs-cell tests.
The set operations and a5_contains require both sides at the same resolution and raise an error otherwise. a5_count and a5_area count overlapping cells more than once β a5_union first when measuring overlapping regions.
Neighborhoods and proximity search
Three traversal primitives, depending on how you define βnearβ:
a5_grid_diskβ all cells withinkedge-steps of a center cell.a5_grid_disk_vertexβ all cells withinkvertex-steps (a slightly wider disk that includes corner-touching cells).a5_spherical_capβ all cells within a metric radius (in meters) of a center cell.
Each returns a covering. Test one cell against it with a5_contains, or a5_uncompact it and probe an indexed cell column with WHERE cell_id IN (SELECT UNNEST(a5_uncompact(...))) β much cheaper than ST_DWithin against raw geometries. Donβt unnest the covering directly: the compacted parents and the trailing marker arenβt the cells you indexed.
GEOMETRY integration
a5_cell_to_geometry and a5_cell_to_point emit DuckDBβs built-in GEOMETRY type directly β a POLYGON for the cell boundary, a POINT for its center β as plain little-endian WKB, with no dependency on the spatial extension to produce them. Load spatial alongside A5 only when you want to run its functions (ST_AsGeoJSON, ST_Intersects, ST_Area, β¦) against a value A5 already gave you:
INSTALL spatial; LOAD spatial;
SELECT ST_AsGeoJSON( a5_cell_to_geometry( a5_lonlat_to_cell(-74.0060, 40.7128, 10) )) AS geojson;a5_geometry_to_cells runs the other direction: it accepts any GEOMETRY (point, line, polygon, or a MULTI*/GEOMETRYCOLLECTION mix) and returns the A5 cells covering it at a chosen resolution. Points map to their containing cell, lines are traced, and polygons are filled by cell-center containment by default; pass overlapping := true to additionally include cells merely touching the boundary, for genuinely gap-free coverage. Polygon holes are excluded, and a geometry with polygon parts comes back as a covering β compacted, with a trailing compaction marker β the same shape a5_compact produces. Point- and line-only geometries return their plain cells in geometry order.
A compacted result is the right shape for storage, transfer, and set operations β but cell boundaries at different resolutions donβt nest geometrically, so rendering a mixed-resolution result directly can show gaps that arenβt really there. Call a5_uncompact first whenever you draw the result on a map, as the Cookbook does β it expands every cell to the resolution the covering was built at and drops the marker.
For the raw vertex data underneath a cellβs boundary β for custom rendering pipelines that donβt go through GEOMETRY β a5_cell_to_boundary returns [lon, lat] pairs directly. The closed_ring variant repeats the first vertex at the end so the result is directly usable as a polygon ring; the segments overload interpolates additional points along each edge for smoother rendering on curved projections.
Cell validity and the world cell
a5_is_valid_cell reports whether a UBIGINT is a canonically-encoded A5 cell rather than an arbitrary integer β useful right after decoding IDs from external data. a5_world_cell returns the single root cell (ID 0) that sits above all twelve resolution-0 cells; itβs the cell 0 that a5_cell_to_boundary special-cases to an empty boundary, since the whole-globe cell has no finite polygon to draw.
Cell IDs from earlier versions
IDs stored by a pre-1.0 version of this extension must be converted once with a5_migrate β UPDATE t SET cell_id = a5_migrate(cell_id). Apply it exactly once and only to pre-1.0 IDs; nothing in an ID records which index produced it. Resolution-1 cells were redefined rather than renumbered, so re-index resolution-1 data from source coordinates. See the Cookbook for a worked example.
Cell IDs as hex strings
A5 IDs round-trip through the canonical 16-character hex form used by the reference A5 library:
SELECT a5_u64_to_hex(a5_lonlat_to_cell(-74.0060, 40.7128, 10));-- '264f798000000000'SELECT a5_hex_to_u64('264f798000000000');-- the corresponding UBIGINTUse a5_u64_to_hex / a5_hex_to_u64 when sharing cell IDs with non-DuckDB code (the upstream JS / TypeScript library expects hex strings; integer storage is more compact inside DuckDB).
Sibling extensions
For other geospatial / spatial-key work in DuckDB:
geosiloβ geographic data utilities, complementary to A5 when you need richer spatial primitives alongside cell-based indexing.lindelβ space-filling curves (Hilbert, Morton). A different approach to the same βflatten 2D into a sortable 1D keyβ problem. Use space-filling curves when you want neighbor locality on a sorted column; use A5 when you want explicit equal-area cell membership.
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Cell Properties
Inspect a specific cell β its area and average edge length in meters, its resolution level, whether it's a validly-encoded cell, and the polygon vertices that form its boundary. Useful for filtering, validation, and rendering cells on a map. |
||
| a5_cell_area() | Object type: Scalar function | Returns the area in square meters of an A5 cell at the specified resolution level (-1 gives the world cell, i.e. |
| a5_cell_edge_length_avg() | Object type: Scalar function | Returns the average edge length in meters of an A5 cell at the specified resolution level; individual edges vary from the average by roughly +/-10% |
| a5_cell_to_boundary() | Object type: Scalar function | Returns the boundary vertices of an A5 cell as a closed ring of [lon, lat] points |
| a5_get_resolution() | Object type: Scalar function | Returns the resolution level (0-30) of an A5 cell |
| a5_is_valid_cell() | Object type: Scalar function | Returns true if the value is a valid A5 cell ID (a canonically-encoded cell). |
|
Cell Sets
Work with regions expressed as lists of cells. Compact a list into a covering (with its trailing compaction marker) and expand it again, count cells and measure area, and combine regions with union, intersection, difference, overlap, and membership tests β all without unnesting. |
||
| a5_area() | Object type: Scalar function | Returns the total area in square meters of a list of A5 cells (compacted or not). |
| a5_compact() | Object type: Scalar function | Compacts a list of A5 cells by merging complete sets of sibling cells into parent cells. |
| a5_contains() | Object type: Scalar function | Returns true if the cell is in the list of A5 cells (compacted or not). |
| a5_count() | Object type: Scalar function | Returns the number of cells in a list of A5 cells at its resolution, i.e. |
| a5_covering_resolution() | Object type: Scalar function | Returns the resolution of a list of A5 cells: the resolution of its compaction marker, or of its finest cell when it has none. |
| a5_difference() | Object type: Scalar function | Returns the difference of two lists of A5 cells: the cells in a but not in b. |
| a5_intersect() | Object type: Scalar function | Returns the intersection of two lists of A5 cells: the cells in both. |
| a5_is_compaction_marker() | Object type: Scalar function | Returns true if the value is a compaction marker: the last element of a covering (as returned by a5_compact, a5_grid_disk, a5_spherical_cap, a5_cell_to_subcells, polygon coverings and the set operations), recording the resolution its cells stand for. |
| a5_overlaps() | Object type: Scalar function | Returns true if two lists of A5 cells (compacted or not) share any cell. |
| a5_uncompact() | Object type: Scalar function | Expands a list of A5 cells to all their cells at the resolution of the list: the resolution of its compaction marker, or of its finest cell when it has none. |
| a5_union() | Object type: Scalar function | Returns the union of two lists of A5 cells: the cells in either. |
|
Coordinate Conversion
Translate between geographic coordinates (longitude/latitude) and A5 cell IDs in their numeric or hex string forms. Use these as your entry and exit points for indexing data into A5. |
||
| a5_cell_to_lonlat() | Object type: Scalar function | Returns the center point [longitude, latitude] of an A5 cell |
| a5_hex_to_u64() | Object type: Scalar function | Converts an A5 hex string representation to a UBIGINT cell ID |
| a5_lonlat_to_cell() | Object type: Scalar function | Converts a longitude/latitude coordinate to an A5 cell at the specified resolution |
| a5_u64_to_hex() | Object type: Scalar function | Converts a UBIGINT A5 cell ID to its hex string representation |
|
Geometry Integration
Convert cells to and from DuckDB's built-in |
||
| a5_cell_to_geometry() | Object type: Scalar function | Returns an A5 cell as a POLYGON geometry of its boundary |
| a5_cell_to_point() | Object type: Scalar function | Returns the center of an A5 cell as a POINT geometry |
| a5_geometry_to_cells() | Object type: Scalar function | Returns the A5 cells covering an arbitrary geometry at the given resolution. |
|
Hierarchy
Navigate up and down A5's 31-level resolution hierarchy. Parents and children follow the cell-ID hierarchy; supercells and subcells follow geometry β the coarser cell that actually contains a cell's center, and the finer cells whose centers lie inside it. |
||
| a5_cell_to_children() | Object type: Scalar function | Returns the immediate child A5 cells (one resolution finer) |
| a5_cell_to_parent() | Object type: Scalar function | Returns the immediate parent A5 cell (one resolution coarser) |
| a5_cell_to_subcells() | Object type: Scalar function | Returns the A5 cells at the specified finer resolution whose centers lie in the cell: the spatial counterpart of a5_cell_to_children and the inverse of a5_cell_to_supercell. |
| a5_cell_to_supercell() | Object type: Scalar function | Returns the A5 cell at the specified coarser resolution that contains the center of the cell: the spatial counterpart of a5_cell_to_parent, whose result need not contain the cell (-1 gives the world cell) |
| a5_get_num_children() | Object type: Scalar function | Returns the number of child cells at child_resolution that fit within a cell at parent_resolution (-1 for the world cell) |
|
Traversal
Find cells in a neighborhood: edge- or vertex-adjacent grid disks for fixed-step traversal, or all cells within a metric radius. Each returns a covering; use these for proximity queries and spatial joins. |
||
| a5_grid_disk() | Object type: Scalar function | Returns all A5 cells within k edge-steps of the given cell (edge adjacency), as a covering: compacted cells sorted in curve order, followed by a compaction marker recording the resolution - use a5_uncompact to expand it |
| a5_grid_disk_vertex() | Object type: Scalar function | Returns all A5 cells within k vertex-steps of the given cell (vertex adjacency), as a covering: compacted cells sorted in curve order, followed by a compaction marker recording the resolution - use a5_uncompact to expand it |
| a5_spherical_cap() | Object type: Scalar function | Returns all A5 cells within the specified radius (in meters) of the given cell, as a covering: compacted cells sorted in curve order, followed by a compaction marker recording the resolution - use a5_uncompact to expand it |
|
Utilities
General-purpose helpers β total cell count at a resolution, the 12 base cells covering the globe at resolution 0 (and the single root world cell above them), the finest resolution, and migration of cell IDs stored by pre-1.0 versions of A5. |
||
| a5_get_num_cells() | Object type: Scalar function | Returns the total number of A5 cells at the specified resolution level (0-30) |
| a5_get_res0_cells() | Object type: Scalar function | Returns all 12 resolution 0 (root) A5 cells covering the entire globe |
| a5_max_resolution() | Object type: Scalar function | Returns the finest A5 resolution level (30). |
| a5_migrate() | Object type: Scalar function | Converts a cell ID created by a pre-1.0 version of A5 (this extension built on the a5 crate 0.10 or earlier) to the ID of the same cell in the A5 1.0 index. |
| a5_world_cell() | Object type: Scalar function | Returns the A5 world cell, the root cell that covers the entire globe and is the ancestor of all resolution-0 cells |
No extension contents match that search.
API Reference
Function Reference
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
Encode a point as a cell ID
The everyday entry point β convert (lon, lat) to a UBIGINT cell ID at a chosen resolution:
SELECT a5_lonlat_to_cell(-74.0060, 40.7128, 15) AS nyc_cell;Output
| nyc_cell |
|---|
| 2760559170984869888 |
Higher resolution = smaller cells. See a5_lonlat_to_cell for the full signature and a5_cell_area for the equal-area cell size at any resolution:
SELECT a5_cell_area(15) AS cell_area_m2;Output
| cell_area_m2 |
|---|
| 31669.04205949599 |
Aggregate point data into cells
The common heatmap pattern β bucket points by cell, then count / sum / aggregate:
SELECT a5_lonlat_to_cell(longitude, latitude, 10) AS cell_id, COUNT(*) AS point_count, AVG(amount) AS avg_amountFROM transactionsGROUP BY cell_idORDER BY point_count DESCLIMIT 100;Because A5 cells are equal-area at each resolution, the resulting counts are directly comparable across latitudes β no per-cell area normalization needed.
Recover the cell center
Round-trip a cell ID back to (lon, lat) for labeling or display:
SELECT a5_cell_to_lonlat(a5_lonlat_to_cell(-74.0060, 40.7128, 15)) AS center_coords;Output
| center_coords |
|---|
| [-74.00764805615836, 40.712802251384296] |
For a GEOMETRY point instead of a raw [lon, lat] array, use a5_cell_to_point.
Render a cell as a polygon
a5_cell_to_geometry returns the cell boundary directly as DuckDBβs built-in GEOMETRY type β no spatial extension needed to produce it. Load spatial only for functions that consume it, like ST_AsGeoJSON:
INSTALL spatial; LOAD spatial;
SELECT ST_AsGeoJSON( a5_cell_to_geometry( a5_lonlat_to_cell(-3.7037, 40.41677, 10) )) AS geojson;The cell at resolution 10 covering Madrid (-3.7037, 40.41677):
Cover a polygon (or point, or line) with cells
a5_geometry_to_cells runs the inverse of a5_cell_to_geometry β hand it any GEOMETRY and a resolution, and it returns the covering set of A5 cells. A plain ::GEOMETRY cast from WKT text works with no extension beyond a5 itself. For a polygon the result is a covering: complete groups of sibling cells collapse to a coarser parent, sorted in curve order, followed by a trailing compaction marker β a UBIGINT that is not a cell but records the resolution the covering stands for (see Coverings and the compaction marker). Thatβs the right shape for storage, transfer, and set operations. But the marker is not a cell, and cell boundaries at different resolutions donβt nest geometrically, so uncompact before unnesting or drawing the cells on a map β a5_uncompact drops the marker and expands every cell to the resolution the covering was built at; skip it and a mixed-resolution result will show gaps that arenβt really there:
SELECT unnest(a5_uncompact( a5_geometry_to_cells( 'POLYGON((-74.02 40.70, -73.99 40.70, -73.99 40.72, -74.02 40.72, -74.02 40.70))'::GEOMETRY, 12 ))) AS cell;Points map to their containing cell, lines are traced, and polygons are filled by cell-center containment by default β which really does leave a gap at the polygonβs edge, visible below where the query rectangleβs left and bottom edges cross cells whose center falls just outside it:
Pass overlapping := true for genuinely gap-free coverage β it additionally includes every cell that merely touches the boundary. Uncompact this one too before drawing it:
SELECT unnest(a5_uncompact( a5_geometry_to_cells( 'POLYGON((-74.02 40.70, -73.99 40.70, -73.99 40.72, -74.02 40.72, -74.02 40.70))'::GEOMETRY, 12, true ))) AS cell;To ask whether a single cell falls inside the covering, skip the unnest entirely β a5_contains probes the compacted covering directly, as long as the cell is at the coveringβs resolution. To join against an indexed cell column, a5_uncompact first and join on the expanded cells β but thatβs a different reason to uncompact than the rendering one above: joins care about matching resolutions, drawing cares about geometric nesting.
Roll up to a coarser resolution
Encode once at the finest resolution youβll need, then re-aggregate at every coarser zoom without re-reading raw points:
-- Encode at resolution 15 onceCREATE OR REPLACE TABLE indexed ASSELECT *, a5_lonlat_to_cell(lon, lat, 15) AS cell_15FROM raw_points;
-- Roll up to resolution 10SELECT a5_cell_to_parent(cell_15, 10) AS cell_10, COUNT(*) AS nFROM indexedGROUP BY cell_10;a5_get_resolution recovers the resolution from a cell ID; a5_get_num_children returns the parent/child cell ratio between two resolutions. Omit the resolution β a5_cell_to_parent(cell_15) β for the immediate parent one level up.
Parent vs supercell
A5 cells donβt nest exactly across resolutions: a cellβs parent is its ancestor in the cell-ID hierarchy, and it need not contain the cell. When you want the coarser cell a point actually lies in β which is usually what a spatial roll-up means β use a5_cell_to_supercell, which returns the coarser cell containing the cellβs center:
SELECT a5_cell_to_parent(c, 5) AS parent, a5_cell_to_supercell(c, 5) AS supercell, a5_lonlat_to_cell(-74.0060, 40.7128, 5) AS containingFROM (SELECT a5_lonlat_to_cell(-74.0060, 40.7128, 15) AS c);Output
| parent | supercell | containing |
|---|---|---|
| 2760143621624692736 | 2761269521531535360 | 2761269521531535360 |
The supercell matches encoding the original point directly at resolution 5; the parent is a neighboring cell. The parent is the cheaper, purely integer walk and is fine for bucketing that only needs to be consistent; use the supercell when the coarse buckets must respect real geography.
Drill down to children
The inverse of roll-up β get the immediate children, or all descendants at a target resolution:
-- Immediate children (one level finer)SELECT a5_cell_to_children(a5_lonlat_to_cell(-74.0060, 40.7128, 10)) AS kids;-- All descendants at resolution 12SELECT a5_cell_to_children(a5_lonlat_to_cell(-74.0060, 40.7128, 10), 12) AS descendants;The spatial counterpart is a5_cell_to_subcells: the finer cells whose centers lie inside the cell β the inverse of a5_cell_to_supercell. The two sets differ slightly at the edges:
SELECT a5_count(a5_cell_to_subcells(a5_lonlat_to_cell(-74.0060, 40.7128, 5), 8)) AS subcells, a5_count(a5_cell_to_children(a5_lonlat_to_cell(-74.0060, 40.7128, 5), 8)) AS children;Output
| subcells | children |
|---|---|
| 62 | 64 |
Subcells come back as a covering, so count them with a5_count rather than len(); the subcells of every cell at one resolution partition each finer resolution exactly.
Neighborhood search by cell-step
a5_grid_disk returns all cells within k edge-steps of a center cell β the typical βk-ringβ pattern from H3:
SELECT unnest(a5_uncompact( a5_grid_disk(a5_lonlat_to_cell(-74.0060, 40.7128, 15), 1))) AS neighbor_cell;Output
| neighbor_cell |
|---|
| 2760557102958116864 |
| 2760559168837386240 |
| 2760559169911128064 |
| 2760559170984869888 |
| 2760559172058611712 |
| 2760559181722288128 |
The center cell and its five edge neighbors. a5_grid_disk itself returns a compacted covering β here three cells plus the trailing compaction marker β so expand it with a5_uncompact before unnesting, or you get coarser parent cells in place of the resolution-15 neighbors they stand for, plus the marker as a bogus row. a5_grid_disk_vertex is the slightly wider variant that includes vertex-touching cells.
Neighborhood search by metric radius
When you have a real-world distance budget rather than a step count:
-- All cells within 5 km of Times Square at resolution 15SELECT a5_spherical_cap(a5_lonlat_to_cell(-74.0060, 40.7128, 15), 5000.0) AS nearby_cells;Thatβs a compacted covering β 248 cells plus the marker standing in for 2,480 resolution-15 cells. Test a single cell against it directly with a5_contains:
WITH cap AS ( SELECT a5_spherical_cap(a5_lonlat_to_cell(-74.0060, 40.7128, 15), 5000.0) AS cells)SELECT a5_contains(cells, a5_lonlat_to_cell(-73.9857, 40.7484, 15)) AS midtown_in_range, a5_contains(cells, a5_lonlat_to_cell(-73.7781, 40.6413, 15)) AS jfk_in_rangeFROM cap;Output
| midtown_in_range | jfk_in_range |
|---|---|
| true | false |
For a join against an indexed cell column, uncompact to the columnβs resolution and probe:
WITH cells AS ( SELECT unnest(a5_uncompact( a5_spherical_cap(a5_lonlat_to_cell(-74.0060, 40.7128, 15), 5000.0) )) AS c)SELECT t.*FROM transactions tJOIN cells ON cells.c = t.cell_15;Coverings and the compaction marker
a5_compact replaces complete groups of sibling cells with their parent β fewer rows to ship, expandable on the consumer side. The four resolution-6 children of a cell compact back to that one resolution-5 cell:
SELECT a5_compact(a5_cell_to_children(a5_lonlat_to_cell(-122.4, 37.8, 5))) AS compacted;Output
| compacted |
|---|
| [1937110789722734592, 17295511418962968640] |
The second element is not a cell. Itβs the compaction marker that ends every covering β from a5_compact, a5_grid_disk, a5_grid_disk_vertex, a5_spherical_cap, a5_cell_to_subcells, the set operations, and polygon results of a5_geometry_to_cells β and it records the resolution the cells stand for. Without it, a covering that compacted down to a single resolution-5 cell would look the same whether it was built at resolution 6 or 12. Read it, and the size of the region, without expanding anything:
WITH c AS (SELECT a5_compact(a5_cell_to_children(a5_lonlat_to_cell(-122.4, 37.8, 5))) AS cells)SELECT a5_covering_resolution(cells) AS resolution, a5_count(cells) AS cell_count, list_filter(cells, lambda x: NOT a5_is_compaction_marker(x)) AS compacted_cellsFROM c;Output
| resolution | cell_count | compacted_cells |
|---|---|---|
| 6 | 4 | [1937110789722734592] |
a5_uncompact is the inverse β it expands a covering to its own resolution and drops the marker:
SELECT a5_uncompact(a5_compact(a5_cell_to_children(a5_lonlat_to_cell(-122.4, 37.8, 5)))) AS expanded;A plain list with no marker is accepted too; its resolution is that of its finest cell. To expand a hand-built list to a resolution of your choosing, expand each cell instead:
SELECT flatten(list_transform( [a5_lonlat_to_cell(-122.4, 37.8, 5)], lambda c: a5_cell_to_children(c, 7))) AS expanded;Combine regions with set operations
Coverings compose directly β a5_union, a5_intersect, and a5_difference return a new covering, a5_overlaps answers yes/no, and a5_area measures the result in square meters. Nothing is unnested along the way:
WITH zones AS ( SELECT a5_spherical_cap(a5_lonlat_to_cell(-74.0060, 40.7128, 13), 3000.0) AS lower_manhattan, a5_spherical_cap(a5_lonlat_to_cell(-73.9903, 40.6928, 13), 3000.0) AS brooklyn_heights)SELECT a5_overlaps(lower_manhattan, brooklyn_heights) AS overlaps, a5_count(a5_union(lower_manhattan, brooklyn_heights)) AS either, a5_count(a5_intersect(lower_manhattan, brooklyn_heights)) AS both_zones, a5_count(a5_difference(lower_manhattan, brooklyn_heights)) AS manhattan_only, round(a5_area(a5_intersect(lower_manhattan, brooklyn_heights)) / 1e6, 2) AS shared_km2FROM zones;Output
| overlaps | either | both_zones | manhattan_only | shared_km2 |
|---|---|---|---|---|
| true | 84 | 30 | 27 | 15.2 |
Both arguments must be at the same resolution β combining a resolution-12 covering with a resolution-13 one is an error, not a silent mix. a5_area and a5_count count overlapping cells more than once, so a5_union two regions before measuring their combined size.
Migrate cell IDs stored before A5 1.0
A5 1.0 renumbered cells along a new curve. The cells themselves are unchanged at resolution 2 and finer, but their IDs are different β and an old ID is still well-formed, so it silently names a different cell instead of failing. a5_migrate converts a pre-1.0 ID to the current one:
SELECT a5_migrate(2742821848331845632) AS migrated, a5_lonlat_to_cell(-74.0060, 40.7128, 15) AS current;Output
| migrated | current |
|---|---|
| 2760559170984869888 | 2760559170984869888 |
2742821848331845632 is the resolution-15 Times Square cell as earlier versions of this extension encoded it. Migrate stored IDs exactly once β nothing in an ID says which index it belongs to, so running it twice corrupts them:
UPDATE indexed SET cell_15 = a5_migrate(cell_15);Resolution-1 cells were redefined in 1.0 rather than renumbered, so a5_migrate leaves their IDs alone; re-index resolution-1 data from its source coordinates instead.
Round-trip cell IDs as hex strings
Useful when sharing cell IDs with the upstream JS / TypeScript A5 library, which uses the canonical 16-character hex form:
SELECT a5_u64_to_hex(a5_lonlat_to_cell(-122.4, 37.8, 10)) AS hex_id;-- '1ae2988000000000'SELECT a5_hex_to_u64('1ae2988000000000') AS cell_id;a5_u64_to_hex and a5_hex_to_u64 are pure conversions β store the UBIGINT form for compactness, hex for interchange.
Spatial join via shared cell ID
Encode both sides at the same resolution and join on the cell ID β much cheaper than ST_Intersects for the βare these in the same neighborhoodβ question:
WITH events AS ( SELECT *, a5_lonlat_to_cell(lon, lat, 12) AS cell FROM event_points),zones AS ( SELECT *, a5_lonlat_to_cell(lon, lat, 12) AS cell FROM zone_centroids)SELECT z.zone_name, COUNT(*) AS event_countFROM events eJOIN zones z USING (cell)GROUP BY z.zone_name;For polygon zones rather than centroids, encode each zone with a5_geometry_to_cells instead and UNNEST(a5_uncompact(...)) the covering before joining.
Inspect the base grid
The 12 root cells covering the entire globe at resolution 0:
SELECT unnest(a5_get_res0_cells()) AS root_cell;a5_get_num_cells returns the total cell count at any resolution (up to a5_max_resolution(), 30) β useful for sizing decisions before encoding a large dataset. a5_world_cell returns the single root cell (ID 0) above all twelve of these; a5_is_valid_cell is a quick sanity check when a UBIGINT came from outside DuckDB β it rejects a cell whose encoded origin points past the 12 base cells, which is the shape of ID corruption youβd actually hit (a bit-flipped or truncated cell), not just any small integer:
SELECT a5_is_valid_cell(a5_lonlat_to_cell(-74.0060, 40.7128, 10)) AS ok, a5_is_valid_cell(63::UBIGINT << 58) AS bogus;Platform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
DuckDB 2.0.0
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS Apple Silicon
- Windows x86_64x86_64 (MinGW)
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 5.32 MB |
| Linux | aarch64 | 4.62 MB |
| macOS | Apple Silicon | 3.21 MB |
| Windows | x86_64 | 10.52 MB |
| Windows | x86_64 (MinGW) | 19.36 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- DuckDB v2.0.0 Query.Farm repository Supported
- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .