Arquitetura medalhão para dado geoespacial com Apache SedonaA medallion architecture for geospatial data with Apache Sedona
Mapa bonito é a última etapa. Antes dele, a geometria precisa ser válida, estar no CRS certo, ter índice espacial e ser resumida na escala que o mapa aguenta. É o mesmo raciocínio Bronze, Silver e Gold que já usamos para tabelas, aplicado a polígonos e pontos.
A pretty map is the last step. Before it, geometry must be valid, in the right CRS, spatially indexed and summarised at a scale the map can bear. It is the same Bronze, Silver and Gold thinking we use for tables, applied to polygons and points.
Por que o dado geoespacial pede cuidado próprioWhy geodata needs its own care
- CRS declarado. Sem saber em qual sistema o dado nasceu (WGS84 em graus, SIRGAS 2000, UTM em metros), nenhuma transformação é confiável. Depois de qualquer reprojeção, confira os limites: milhões indicam metros, valores pequenos indicam graus.
- Geometria válida. Polígonos que se auto-intersectam quebram uniões e interseções.
ST_MakeValidentra na Silver. - Medir em projeção métrica. Um buffer de "100 km" em graus erra a área em quase 9% em São Paulo; em UTM o círculo está certo.
- Discretizar para escalar. Com milhões de pontos, resuma por hexágono (H3) em vez de rodar estatística ponto a ponto.
- Classificar e colorir é decisão metodológica. Quantis, intervalo igual e quebras naturais contam histórias diferentes; e paleta divergente só faz sentido quando existe um centro.
- A declared CRS. Without knowing where the data was born (WGS84 degrees, SIRGAS 2000, UTM metres), no transform is trustworthy. After any reprojection check the bounds: millions mean metres, small numbers mean degrees.
- Valid geometry. Self-intersecting polygons break unions and intersections.
ST_MakeValidbelongs in Silver. - Measure in a metric projection. A "100 km" buffer in degrees gets the area wrong by almost 9% in São Paulo; in UTM the circle is right.
- Discretise to scale. With millions of points, summarise per hexagon (H3) instead of running point-by-point statistics.
- Classifying and colouring is a methodological decision. Quantiles, equal interval and natural breaks tell different stories; and a diverging palette only makes sense when there is a centre.
A arquiteturaThe architecture
Sedona leva as funções ST_* do PostGIS para o Spark SQL, então o mesmo código roda de um notebook até um data lake. O que o Sedona não faz (densidade de núcleo, quebras naturais de Fisher-Jenks) fica no cliente Python, depois de agregar em H3.
Sedona brings PostGIS-style ST_* functions to Spark SQL, so the same code runs from a notebook to a data lake. What Sedona does not do (kernel density, Fisher-Jenks natural breaks) stays on the Python client, after aggregating into H3.
O que foi executado. As figuras do blog foram geradas por Python (geopandas, shapely, h3, matplotlib) sobre os mesmos dados. O SQL do Sedona 1.7.1 está no notebook notebooks/sedona_geo_medallion.py, escrito para Databricks, com verificações de paridade contra os números do Python. Eu não executei esse notebook em um cluster Spark.
What was executed. The figures on this blog were produced by Python (geopandas, shapely, h3, matplotlib) over the same data. The Sedona 1.7.1 SQL is in notebooks/sedona_geo_medallion.py, written for Databricks, with parity checks against the Python numbers. I have not run that notebook on a Spark cluster.
Rodando no DatabricksRunning on Databricks
No cluster (modo de acesso dedicado), instale apache-sedona do PyPI e as bibliotecas Maven abaixo, compatíveis com o Spark 3.5 do runtime. Depois crie o contexto e use sedona.sql.
On the cluster (dedicated access mode), install apache-sedona from PyPI and the Maven libraries below, matching the runtime's Spark 3.5. Then create the context and use sedona.sql.
org.apache.sedona:sedona-spark-shaded-3.5_2.12:1.7.1
org.datasyslab:geotools-wrapper:1.7.1-28.5
from sedona.spark import SedonaContext
sedona = SedonaContext.create(spark)
sedona.read.format("geojson").option("multiLine", "true").load(path)
Os GeoJSON de São PauloThe São Paulo GeoJSON files
Quatro divisões territoriais, cada uma em GeoJSON e em TopoJSON (menor). Coordenadas em WGS84 (longitude, latitude).
Four territorial divisions, each as GeoJSON and as the smaller TopoJSON. Coordinates in WGS84 (longitude, latitude).