# Spatial > Responde preguntas sobre datos espaciales con DuckDB: ubicaciones, coordenadas, distancias, mapas, direcciones, formatos como GeoJSON, Shapefile, GeoPackage, GPX o GeoParquet, usando también Overture Maps. Fuente: https://skillsagentes.com/skills/duckdb/duckdb-skills/spatial Markdown: https://skillsagentes.com/skills/duckdb/duckdb-skills/spatial.md Repositorio: https://github.com/duckdb/duckdb-skills Autor: duckdb Licencia: MIT Actualizado: hace 5 meses Coste de contexto: 132 tok instalada, 1k tok al activarse, 3.9k tok con todos los archivos del bundle Bundle: 3 archivos, 15 KB Permisos que pide: bash ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add duckdb/duckdb-skills --skill spatial --agent claude-code # Cursor npx -y skills add duckdb/duckdb-skills --skill spatial --agent cursor # Codex npx -y skills add duckdb/duckdb-skills --skill spatial --agent codex # Gemini CLI npx -y skills add duckdb/duckdb-skills --skill spatial --agent gemini # Windsurf npx -y skills add duckdb/duckdb-skills --skill spatial --agent windsurf # Cline npx -y skills add duckdb/duckdb-skills --skill spatial --agent cline ``` ## Qué hace - Ejecuta consultas espaciales en DuckDB usando la extensión spatial y, cuando hace falta, datos globales gratuitos de Overture Maps en S3 - Clasifica la pregunta del usuario en un patrón (cercanía, distancia, contención, densidad, conversión) y elige la fuente de datos y funciones adecuadas - Configura siempre `LOAD spatial;` y `SET geometry_always_xy = true;` antes de ejecutar consultas - Convierte entre formatos geográficos (GeoJSON, Shapefile, GeoPackage, GPX, GeoParquet) usando `ST_Read` y `COPY TO (FORMAT GDAL)` - Calcula distancias reales con `ST_Distance_Spheroid` y realiza binning hexagonal H3 para análisis de densidad ## Cuándo usarla - El usuario menciona ubicaciones, coordenadas, lat/lng, distancias, mapas, direcciones, "cerca", "dentro de" o "más cercano" - El usuario quiere analizar o convertir archivos GeoJSON, Shapefile, GeoPackage, GPX o GeoParquet - El usuario busca lugares, edificios o carreteras reales sin proporcionar un archivo propio - El usuario pide contar elementos geográficos, unir espacialmente datos o detectar patrones de densidad ## Qué la activa - "Encuentra restaurantes cerca de esta dirección usando Overture Maps" - "Convierte este archivo Shapefile a GeoJSON" - "¿Cuántos edificios hay dentro de este polígono?" - "Calcula la distancia real entre estos dos puntos lat/lng" - "Muestra zonas de mayor densidad de carreteras en esta ciudad" ## Antes de instalar - Requiere DuckDB con las extensiones spatial (y opcionalmente httpfs y h3 desde community) instaladas, y credenciales de AWS si se accede a Overture Maps en S3. - runs shell commands ## Archivos - SKILL.md — 4 KB - references/functions.md — 6 KB - references/overture.md — 5 KB ## SKILL.md Reproducido tal cual desde duckdb/duckdb-skills bajo MIT. Esta sección es el documento original y está en inglés. You are answering spatial questions using DuckDB's spatial extension and, when needed, Overture Maps as a free global data source. Question or file: `$0` Additional context: `${1:-}` ## Step 1 — Understand what the user needs Classify the question: | Pattern | Data source | Key functions | |---------|-------------|---------------| | "Find X near Y" (no user file) | Overture Maps on S3 | `ST_Distance_Spheroid`, bbox filtering | | "How far between A and B" | Geocode or user data | `ST_Distance_Spheroid` | | "Which points fall inside polygons" | User files | `ST_Contains` | | "Analyze this GeoJSON/Shapefile/GPX" | User file | `ST_Read`, measurement functions | | "Show density/hotspots" | User or Overture data | H3 hex binning | | "Convert to GeoJSON/GeoPackage" | User file | `COPY TO (FORMAT GDAL)` | | "Count buildings/roads in area" | Overture Maps | bbox filtering + aggregation | If the question involves real-world places, POIs, buildings, roads, or boundaries and the user hasn't provided a file, use **Overture Maps** — read `references/overture.md` for S3 paths and schema. For spatial function syntax, read `references/functions.md`. ## Step 2 — Write and run the query Always start with: ```sql LOAD spatial; SET geometry_always_xy = true; ``` Add extensions as needed: - Overture/remote data: `LOAD httpfs; CREATE SECRET (TYPE S3, PROVIDER config, REGION 'us-west-2');` - H3 hex binning: `INSTALL h3 FROM community; LOAD h3;` ### Key principles **bbox filtering first** — When querying Overture, always filter on `bbox.xmin/xmax/ymin/ymax` before any spatial function. This uses Parquet predicate pushdown and avoids downloading the full dataset. **Always set `geometry_always_xy = true`** — This ensures all spatial functions interpret coordinates as longitude, latitude (the standard for Overture, GeoJSON, and most data sources). Without it, spheroid functions assume latitude first and return wrong results. **Use spheroid functions for real-world distances** — `ST_Distance_Spheroid` returns meters on the WGS84 ellipsoid. Plain `ST_Distance` uses planar coordinates and gives meaningless results for lat/lng. **Important:** spheroid functions (`ST_Distance_Spheroid`, `ST_Area_Spheroid`, etc.) require `POINT_2D` inputs, not generic `GEOMETRY`. Overture geometry columns are typed `GEOMETRY('OGC:CRS84')` and cannot be cast directly. Extract coordinates first: ```sql ST_Point(ST_X(geometry), ST_Y(geometry))::POINT_2D ``` **CSV with lat/lng needs conversion** — `ST_Point(longitude, latitude)` (longitude first). This is the most common gotcha. Run the query in a single bash call: ```bash duckdb -c " LOAD spatial; " ``` ## Step 3 — Present results - For tabular results: show the data directly - For spatial results: consider exporting to GeoJSON for visualization (`COPY TO 'result.geojson' WITH (FORMAT GDAL, DRIVER 'GeoJSON')`) - For distance/area results: use human-readable units (km for large distances, m for small) - For density/hotspot results: describe the pattern and offer to export for visualization If the query fails: - **`duckdb: command not found`** → delegate to `/duckdb-skills:install-duckdb` - **Missing extension** → `INSTALL spatial; LOAD spatial;` or `INSTALL h3 FROM community; LOAD h3;` - **S3 access denied** → suggest checking AWS credentials - **No results with Overture** → widen the bbox, check the category spelling, or try a broader search ## Dónde encaja - Categoría: [Datos y analítica](https://skillsagentes.com/categorias/datos-analitica.md) — Consulta, limpia y visualiza datos sin salir del agente. - Creador: [duckdb](https://skillsagentes.com/creators/duckdb.md) — 0 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [S3 Explore](https://skillsagentes.com/skills/duckdb/duckdb-skills/s3-explore.md): Explora y consulta datos en S3, Cloudflare R2, GCS, MinIO o cualquier almacenamiento compatible con S3, sin necesidad de descargarlos. - [Convert File](https://skillsagentes.com/skills/duckdb/duckdb-skills/convert-file.md): Convierte cualquier archivo de datos a otro formato: CSV, Parquet, JSON, Excel, GeoJSON y más, usando DuckDB. - [Duckdb Docs](https://skillsagentes.com/skills/duckdb/duckdb-skills/duckdb-docs.md): Busca en la documentación de DuckDB y DuckLake y en posts del blog, devolviendo fragmentos relevantes mediante búsqueda de texto completo contra un índice local cacheado. - [Read File](https://skillsagentes.com/skills/duckdb/duckdb-skills/read-file.md): Lee cualquier archivo de datos (CSV, JSON, Parquet, Avro, Excel, spatial, SQLite) o URL remota (S3, HTTPS) usando DuckDB. No sirve para código fuente. - [Read Memories](https://skillsagentes.com/skills/duckdb/duckdb-skills/read-memories.md): Busca en los logs de sesiones pasadas de Claude Code para recordar decisiones, patrones o trabajo pendiente. Úsalo cuando el usuario mencione conversaciones anteriores o necesites contexto previo. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)