Repository navigation
Geospatial
Tier: Intermediate
Commands covered: geocode, geoconvert
Note
Per-command flag reference lives in /docs/help/. This page is the workflow layer — when to reach for each command and how they compose.
Two commands, big footprint. geocode handles forward geocoding, reverse geocoding, city suggestions, IP geolocation, and country info — all against a local Geonames index plus an optional MaxMind GeoLite2 database. No network round-trip per row, 360,000 records / sec with caching and multithreading. It can also geocode online via the OpenCage API (the opencage / opencagenow subcommands) when you need true street-address geocoding that the local city index can't do. For New York City, the geoclient / geoclientnow subcommands use NYC's own Geoclient API, which also returns BBLs, BINs, council districts, census tracts and other NYC attributes.
geoconvert flips between CSV/SVG and spatial formats (GeoJSON, GeoJSONL, SHP).
| If you want to… | Use | Notes |
|---|---|---|
| Find lat/lon from a city name | geocode suggest |
Jaro-Winkler fuzzy matching |
| Resolve small-town place names the default index misses | geocode index-load 1000 |
New in 23.0.1 — the denser cities1000 prebuilt (details) |
| Find the nearest city to a lat/lon | geocode reverse |
Local index; no API rate limits |
| Find country code from an IP | geocode iplookup |
Needs MaxMind GeoLite2-City.mmdb |
| Enrich with US state/county FIPS codes |
geocode suggest / reverse with FIPS dyncols |
Census data prep |
| Geocode a full street address (online) | geocode opencage |
OpenCage API; needs an API key |
| Reverse-geocode a coordinate to a full address (online) | geocode opencage |
Same subcommand; mode auto-detected |
| Geocode a New York City address, BBL or BIN (online) | geocode geoclient |
NYC Geoclient API; needs a free NYC API key (details) |
| Manage / prune the OpenCage and Geoclient result caches | geocode cache-* |
cache-clear, cache-prune, cache-info
|
| CSV → GeoJSON for QGIS / web maps | geoconvert |
Specify --geometry for WKT or lat/lon |
| GeoJSON / SHP → CSV | geoconvert |
Drops to a flat tabular form |
| Plot lat/lon points on an interactive map | viz map |
Tile basemap; point or --density heatmap |
| Plot lat/lon on an offline projection map | viz geo |
ScatterGeo projection — no tiles or token; --projection
|
Nineteen subcommands; the big four are suggest, suggestnow, reverse, reversenow. Plus iplookup / iplookupnow, countryinfo / countryinfonow, the online opencage / opencagenow and geoclient / geoclientnow subcommands, the geocode index-* subcommands for managing the local Geonames cities index, and the geocode cache-* subcommands for managing the on-disk OpenCage and Geoclient result caches.
# Downloads the prebuilt Geonames cities15000 index (~26k cities, pop > 15k)
qsv geocode suggest --help # first run triggers the download
# Manage the local index
qsv geocode index-check # show index metadata; check for updates
qsv geocode index-update # rebuild from the latest Geonames data
qsv geocode index-load my_index.rkyv # load a custom-built .rkyv index file
qsv geocode index-load 1000 # NEW in 23.0.1 — fetch the denser cities1000 prebuilt
qsv geocode index-reset # restore the default prebuilt cities15000 indexOld indexes are cleaned up automatically (Unreleased, after 24.0.0, #4776). The index file is named for the qsv release (
qsv-24.0.0-geocode-index.rkyv), so every upgrade downloads a new one, and older releases never removed the previous ones. A long-lived~/.qsv-cache/could hold gigabytes of them. Now, when qsv downloads a new release's index, it keeps the index files of the 5 most recent releases and deletes the rest, printing what it removed. Only files named the way qsv names them are touched. Backups (.bak) and other files stay, and the active index (including one picked withQSV_GEOCODE_INDEX_FILENAME) is always kept. Runqsv geocode index-resetto clean up an existing cache right away.
index-updatekeeps your index's city set and languages (Unreleased, after 24.0.0, #4786).--cities-urland--languagesused to default to cities15000 anden, so a plainindex-updateon a cities1000 or multi-language index rebuilt it as cities15000 with English only. They now default to what the current index was built with. Passing a different value forces a rebuild.--languagesis case-insensitive and ignores spaces (EN, frworks), and--forcecan build an index when none exists yet.
No more blank region names (Unreleased, after 24.0.0, #4786). Region (admin1), county (admin2) and country names used to print blank when the index had no translation for them in the requested language, as the city name never did.
"Maputo, MZ"is now"Maputo, Maputo City MZ". This happened even on the default English index, for about 5% of cities in a world-wide sample. A-l/--languagethe index wasn't built with now prints a warning that says how to rebuild for it.
For IP-based lookups, manually download GeoLite2-City.mmdb from your MaxMind account (free) and copy it to ~/.qsv-cache/ (or set QSV_GEOIP2_FILENAME).
The default index is cities15000 — every populated place with a population over 15,000. That floor is usually the binding constraint when a place name fails to resolve: the town exists in Geonames, just not in this index.
New in 23.0.1: index-load accepts a published population floor as a shortcut, and 1000 now joins 15000 as a published prebuilt. So reaching the denser index is one command instead of a full local rebuild.
| Floor | Places | Prebuilt index | Download | How to get it |
|---|---|---|---|---|
15000 (default) |
~26k worldwide | 22.6 MiB | — | ships by default; geocode index-reset restores it |
1000 |
~140k worldwide | 82.7 MiB (32 MiB compressed) | one command | qsv geocode index-load 1000 |
index-load <floor> downloads a prebuilt, English-only index built for your qsv version. Contrast with qsv geocode index-update --cities-url 1000, which is the old route: it pulls the ~200 MB Geonames source dump and rebuilds from scratch — still the right call when you need non-English place names (its --languages option), but slow and unnecessary if you only want more coverage in English.
Important
The global default is deliberately unchanged. index-load swaps the index for every subsequent geocode run, and a denser index costs roughly 4× the index size and gives different suggest results — a small town can now outrank the large city you were matching before. Load 1000 because your data is full of small places, not as a blanket upgrade.
It is also not a fix for cross-country mis-resolution (a US city name matching a same-named place abroad). That is a country-filter problem, not a density problem, and it reproduces identically against a cities1000 index — constrain the lookup with --country instead.
A floor this binary knows about can still be missing from the release it was built from. When that happens the download failure now names the release and points at the local-rebuild alternative instead of surfacing a bare 404.
Three user-visible bugs in index-load were fixed in 23.0.1. The headline: on 22.0.1 and earlier, index-load did not work at all.
-
index-loadno longer rejects every index as invalid — including qsv's own published prebuilt. Both forms failed, and the command contradicted itself within a single run, printingValid: /tmp/15000.rkyvand then a usage error saying that same file was in an unsupported format. The two code paths were asking different questions of the same file; validation now goes through the same metadata API thatindex-checkuses, against the resolved path. The prematureValid:line is gone — it came from a helper that only checked the file's extension and existence, so it now reportsFound index file:and validity is reported only once the index has actually loaded. This was never a recent regression: the bad gate shipped in 37 releases starting with 10.0.0, unnoticed because the subcommand had no success-path test. It has one now. -
The numeric shortcut no longer litters the working directory.
qsv geocode index-load 1000downloaded to its bare argument as a relative path, dropping files named1000and1000.rkyvinto whatever directory you happened to run it from. The payload is now staged in the geocode cache dir under a descriptive name (cities1000.rkyv.sz), where it doubles as a warm copy for a later re-install. Any stray1000,1000.rkyv,15000or15000.rkyvfiles left behind in old working directories are safe to delete. -
index-loadinstalls a working index, not a corrupt one it reports as a success. Having accepted a valid index, it then re-serialized the loaded engine in order to install it, producing a file that came out short and could not be loaded at all (Error initializing Engine: subtree pointer overran range) — while the command printed a success message. It now copies the file, which is exact and cannot corrupt it, and a failed copy is an error rather than being silently ignored. This defect was only reachable after the validity fix above, so no released version could hit it — nothing to clean up retroactively.
Caution
A failed download is no longer written to disk as if it were the file. Fixed in 23.0.1, and it reaches well past geocode. util::download_file streamed whatever the server returned and never checked the HTTP status, so a 404 page became the payload — an HTML "Not Found" body saved as a Geonames index, a JSON Schema, or a CSV, with the failure surfacing much later as a baffling parse error about the contents. It now fails on any non-2xx response and names the status. This affected every download path: geocode index fetches, validate's remote JSON Schema, and sample / snappy remote inputs. Remediation: check ~/.qsv-cache/ (or $QSV_CACHE_DIR) for an implausibly small index file — an HTML error body is a few hundred bytes where a real index is tens of megabytes.
Example: enrich a list of city names with coordinates
# input has a "city" column with values like "Brooklyn", "san jose", "PARIS"
qsv geocode suggest city \
--new-column 'lat,lon' \
--formatstr "%latitude,%longitude" \
cities.csv > cities_with_coords.csvExample: US-only suggestion that also pulls FIPS codes (for Census joins)
qsv geocode suggest city_col --country US -f \
"%dyncols: {geocoded_city:name},{state:admin1},{county:admin2},\
{state_fips:us_state_fips_code},{county_fips:us_county_fips_code}" \
voters.csv -o voters_with_fips.csvThe %dyncols: directive expands to multiple new columns named on the left of each : pair.
Restricting to a state or province (--admin1)
# a column of Florida city names
qsv geocode suggest city --admin1 US.FL -f "{name}, {admin1}" fl_cities.csv-
--admin1is a strict filter. Only a place inside the listed admin1s is returned. A value with no match there is left unchanged (or set to--invalid-result), and stderr reports how many. Before,suggestfell back to the best match anywhere, soInvernessunderUS.FLcame back as Inver Grove Heights, Minnesota. Small towns missing from the default index are the usual cause of a miss, andindex-load 1000finds more of them (choosing a population floor). -
US territories work:
US.PR,US.VI,US.GU,US.ASandUS.MP. Geonames files them as countries of their own, so--admin1 US.PRused to find no Puerto Rico place at all (Ponce came back as Ponca City). An explicit--country USadmits them too. -
Mixed code lists infer every country, so
--admin1 US.NY,US.PRneeds no--country. Admin1 names still need--country. -
Admin1 codes are case-insensitive (Unreleased, after 24.0.0, #4786):
--admin1 us.caworks likeUS.CA. Before, only the territory codes (us.pr) were accepted in lowercase. Matching is by prefix, and a few full Geonames codes are prefixes of others:KZ.12also matchesKZ.12510143. -
Exact names win. The fuzzy search treats any name that merely starts with the value as a perfect match and breaks ties by population, so "Davis" used to return San Diego. A place whose own name is the value now wins, with or without
--admin1.
Example: reverse-geocode NYC 311 lat/lon to Borough / NTA
qsv geocode reverse 'Location' \
--new-column 'nearest_city,admin1,admin2' \
--formatstr "%name,%admin1,%admin2" \
--country US \
NYC_311_SR_2010-2020-sample-1M.csv > nyc311_reversed.csvLocation is the source column in "lat, lon" or "(lat, lon)" format.
Example: reverse-geocode FIPS codes for downstream Census tract joins
qsv geocode reverse coordinate_col --country US -f \
"%dyncols: {city:name},{state:admin1},{county:admin2},\
{state_fips:us_state_fips_code},{county_fips:us_county_fips_code}" \
events.csv -o events_with_fips.csvCensus joins need the 5-digit county GEOID.
us_county_fips_codeis the 3-digit county part (003), unique only within a state — prefix it withus_state_fips_code(e.g.-f '{us_state_fips_code}{us_county_fips_code}'→42003). 24.0.0 and earlier (#4771): any county code ≥ 100 came out with its first digit dropped (510→010), usually naming a different real county. This is fixed in Unreleased (after 24.0.0); regenerate files enriched by older versions. See US Census Integration.
For ad-hoc one-off lookups from the command line (not a CSV):
qsv geocode suggestnow "Brooklyn"
qsv geocode reversenow "40.6782, -73.9442"
qsv geocode countryinfonow USNeeds the MaxMind GeoLite2-City.mmdb.
qsv geocode iplookup --new-column country ip_col logs.csv > logs_with_country.csvqsv geocode countryinfo country_code visitors.csv > with_country_info.csv
# Adds columns: name, capital, area, population, languages, currency, ...suggest / reverse are city-level and offline — fast, but they can't resolve a full street address. When you need real address geocoding, opencage calls the online OpenCage API. One subcommand does forward (address → coordinates) and reverse (coordinates → address) geocoding — the mode is auto-detected per row (pass --reverse to force reverse).
Requires an OpenCage API key — set it with --api-key or the QSV_OPENCAGE_API_KEY environment variable. A free key allows 2,500 requests/day: https://opencagedata.com/users/sign_up.
# forward-geocode a column of street addresses to coordinates
qsv geocode opencage address --new-column coordinates -f %location addresses.csv
# reverse-geocode "(lat, lon)" coordinates to a full formatted address (the default format)
qsv geocode opencage Location --reverse --new-column address events.csv
# pull individual OpenCage components with dotted dynamic formatting
qsv geocode opencage address -f '{components.city}, {components.country}' addresses.csv
# add multiple columns in one pass with the %dyncols: directive
qsv geocode opencage address \
-f '%dyncols: {city:components.city}, {postcode:components.postcode}, {tz:annotations.timezone.name}' \
addresses.csv
# one-off lookups from the shell
qsv geocode opencagenow "1600 Pennsylvania Ave NW, Washington DC"
qsv geocode opencagenow "40.71427, -74.00597"OpenCage's terms of service permit caching, so results are kept in a persistent on-disk cache (separate from the Geonames index, in {cache-dir}/geocode-opencage_v1) — re-runs and duplicate queries never re-hit the API (--cache-ttl sets the TTL; --no-cache disables it). Rows are processed sequentially behind a rate limiter (--rate-limit, default 1 request/sec — the free-tier limit), so reach for opencage for enrichment quality and for the offline subcommands for raw throughput. Inspect and clean up that cache with the cache-* subcommands.
OpenCage --formatstr options: %formatted (default — the full formatted address), %lat-long, %location, %city, %state, %county, %country, %country_name, %postcode, %confidence, %json, %pretty-json; plus dotted dynamic keys {components.<name>} and {annotations.<dotted.path>}. The %dyncols: directive works here too — %dyncols: {city:components.city}, {tz:annotations.timezone.name} adds several columns to the output CSV in one pass (it cannot be combined with --new-column).
New (Unreleased, after 24.0.0, #4789).
For New York City data, geoclient geocodes through the city's own Geoclient v2 API, a REST wrapper around the Department of City Planning's Geosupport. Beyond coordinates it returns the NYC identifiers and districts that general geocoders don't have: BBL, BIN, community district, city council district, census tracts (2010 and 2020), NTA, ZIP code, and many more fields. It only geocodes locations in the five boroughs.
The public API needs a free subscription key: sign up at https://api-portal.nyc.gov and subscribe to the "Geoclient V2 User" product. Pass it with --api-key or the QSV_GEOCLIENT_API_KEY environment variable. qsv sends the key as a request header, so it never appears in a URL or a log. To use a self-hosted Geoclient instead, set QSV_GEOCLIENT_API_URL to its base URL (e.g. http://localhost:8080/geoclient/v2). A self-hosted instance needs no key and has no quota.
--endpoint picks the kind of lookup:
| Endpoint | Input |
|---|---|
search (default) |
A free-form location in the column: 314 W 100 St Manhattan, a landmark, an intersection, a BBL or a BIN |
bin |
A Building Identification Number |
bbl |
A Borough-Block-Lot: 1000670001, 1-67-1, 1/00067/0001, or a spreadsheet float such as 1000670001.0
|
address, addresspoint, intersection, place, blockface
|
Several columns, mapped with --params
|
# free-form NYC addresses -> "lat, lon" (the default format)
qsv geocode geoclient address --api-key YOURKEY nyc_311.csv
# BBLs (e.g. from PLUTO) -> separate latitude/longitude columns
qsv geocode geoclient bbl --endpoint bbl -f '%dyncols: {lat:latitude}, {lng:longitude}' pluto.csv
# structured address columns -> BBL and council district in new columns
qsv geocode geoclient Street --endpoint address \
--params "houseNumber={HouseNo},street={Street},borough={Borough}" \
-f '%dyncols: {bbl:bbl}, {council:cityCouncilDistrict}, {tract:censusTract2020}' \
permits.csv
# one-off lookups
qsv geocode geoclientnow "350 5th Ave Manhattan"
qsv geocode geoclientnow --endpoint bbl -f '%pretty-json' 1008350041--params maps Geoclient parameter names to input columns (name={Column}) or to fixed values (name=value). Parameter names are case-sensitive, and are checked before any request is sent:
-
address,addresspoint:houseNumber,street, andboroughorzip -
intersection:crossStreetOne,crossStreetTwo,borough, plus optionalboroughCrossStreetTwoandcompassDirection -
place:name, andboroughorzip -
blockface:onStreet,crossStreetOne,crossStreetTwo,borough, plus optionalboroughCrossStreetOne,boroughCrossStreetTwoandcompassDirection
A borough can be a name, an abbreviation (MN, BX, BK, QN, SI) or a number from 1 to 5. With a structured endpoint, the <column> argument is not sent to the API. It only names the column that is replaced with the result, or that --rename applies to. Use -c to add the result as a new column instead. For search, --params can set fixed search options such as exactMatchMaxLevel=5.
Formats: %+ / %lat-long (default), %location, %bbl, %bin, %json, %pretty-json, {field} templates with any result field (e.g. "{bbl} - CD {communityDistrict}"), and %dyncols:. Geosupport pads some fields with spaces, such as censusTract2020; qsv trims them. A field missing from a result renders empty. bbl and bin lookups return no street-front coordinate, so for those latitude/longitude are the building's internal label point.
Throughput and quotas: there is no batch endpoint, so every distinct location is one request. The public API allows 100 requests/second per IP, 2,500/minute and 500,000/day. qsv sends --jobs requests at a time behind a rate limiter. The limiter defaults to 40 requests/second, just under the per-minute cap; set it with --rate-limit. Repeated locations within a batch are looked up once, results are cached on disk, and a location Geoclient can't geocode is left unchanged or set to --invalid-result. Rate-limited and server-error responses are retried up to 3 times. If 10 requests in a row still fail, the run stops with a message about the quota rather than grinding through the rest of the file. A bad key stops it at the first request.
The opencage and geoclient subcommands keep their results in persistent on-disk caches: {cache-dir}/geocode-opencage_v1 and {cache-dir}/geocode-geoclient_v1 (the default cache dir is ~/.qsv-cache/). Only those subcommands populate them; the Geonames cities index is managed separately with index-*. Three subcommands manage the caches, and each one applies to both. (Unreleased, after 24.0.0, #4789: before Geoclient, they covered the OpenCage cache only. cache-info now prints one JSON line per cache, with a provider field.)
# wipe the entire OpenCage and Geoclient caches
qsv geocode cache-clear
# delete entries older than a relative age (s/m/h/d/w suffix) or an absolute date
qsv geocode cache-prune --older-than 30d
qsv geocode cache-prune --older-than 2025-01-01
# report the cache dir, entry count, on-disk size and oldest/newest timestamps (JSON)
qsv geocode cache-infocache-prune is the tool for honoring data-retention policies without discarding the whole cache; cache-info emits a JSON summary you can pipe into other commands.
See also: /docs/help/geocode.md, Geonames, MaxMind GeoLite2, OpenCage API, NYC Geoclient, Recipe: Geographic Enrichment, Lookup Tables — for fallback when geocode misses.
Convert between CSV/SVG and spatial formats. Input formats: geojson, shp (Shapefile), csv. Output formats: csv, svg, geojson, geojsonl — the exact set depends on the input format (see qsv geoconvert --help).
Example: GeoJSON → CSV (for SQL analysis)
qsv geoconvert nta_boundaries.geojson geojson csv > nta.csv
qsv sqlp nta.csv "SELECT borough, COUNT(*) FROM nta GROUP BY borough"Example: CSV with WKT geometry → GeoJSON for a web map
qsv geoconvert parcels.csv csv geojson --geometry geometry > parcels.geojsonExample: SHP → CSV (drops to tabular form)
qsv geoconvert nyc_boroughs.shp shp csv > nyc_boroughs.csvExample: pick a file via dialog, then convert
qsv prompt -m 'Choose a GeoJSON file' -F geojson \
| qsv geoconvert - geojson csv > result.csvExample: combine geocode + geoconvert to enrich and map
# 1. Reverse-geocode NYC 311 to get the borough column
qsv geocode reverse 'Location' --new-column 'borough' \
--formatstr "%admin2" --country US nyc311.csv > step1.csv
# 2. Bulk-convert lat/lon pairs into WKT, then to GeoJSON
qsv apply operations wkt_point Latitude Longitude \
--new-column geometry step1.csv > step2.csv
qsv geoconvert step2.csv csv geojson --geometry geometry > nyc311.geojsonSee also: /docs/help/geoconvert.md, geocode, Conversion & I/O.
- Command Reference (index)
-
Visualization (viz) —
viz map(tile basemap) andviz geo(offline projection) plot lat/lon coordinates on an interactive map - Conversion & I/O — broader I/O context
- HTTP & Web — when you need API-based geocoding (e.g., Google, Mapbox) instead of local
- Cookbook → Geographic Enrichment
- Lookup Tables — fallback patterns for unmatched rows
- Performance Tuning — multithreading & caching
qsv — GitHub · Releases · Discussions · crates.io · qsv pro · Try it online · Benchmarks · DeepWiki · DOI · Licensed MIT · Third-party notices · AI Policy
qsv was made possible by datHere: standards-based, best-of-breed, open source solutions to make your Data Useful, Usable & Used.
Edit this page: Contributing to the Wiki
Home · Why qsv? · Tier legend
- Whirlwind Tour · Notebooks · Lessons & Exercises
- Benchmarks · Interactive Benchmarks
- Visualizations Gallery
- Neuro-symbolic, Localizable, Data Schematics
- Feature Flags · Goals/Non-goals · Testing
- Talks: NYC SOD 2022 · csv,conf,v8 · PyCon US 2025 · csv,conf,v9 · NYC SOD 2026
- "Have we achieved ACI?" series: 1 · 2 · 3 · 4
- Sponsor
- All Commands (index)
- Selection & Inspection
- Transform & Reshape
- Aggregation & Statistics
- Joins & Set Ops
- SQL & Polars
- Validation & Schema
- Metadata Profiling (profile)
- Conversion & I/O
- Geospatial
- Visualization (viz)
- HTTP & Web
- Get & Disk Cache
- Scripting (Luau / Python)
- Indexing, Compression & Diff
- AI & Documentation
- Recipes index
- Inspect an Unknown CSV
- Clean & Normalize
- Geographic Enrichment
- Date Enrichment
- CKAN Integration
- DCAT-US v3 for data.gov
- JSON Schema Validation
- Round-Trip SAS / Stata / SPSS
- Build a Data Pipeline
- Stats → Insights
- Data-Quality Signals with moarstats
- Group By
- Time Buckets
- Fetch & Cache
- Larger-than-RAM CSV
- Diff & Audit
- Multi-table Joins
- Synthesize Fake Data
- Performance Tuning
- Benchmarks
- Tuned csv Fork Benchmarks
- Security & Dependency Audits
- Environment Variables
- Stats Cache & Caching
- Lookup Tables
- MiniJinja Templating