Skip to content
Joel Natividad edited this page Oct 9, 2026 · 33 revisions

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.

geoconvert flips between CSV/SVG and spatial formats (GeoJSON, GeoJSONL, SHP).

Quick decision table

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
Manage / prune the OpenCage result cache 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

geocode

Seventeen subcommands; the big four are suggest, suggestnow, reverse, reversenow. Plus iplookup / iplookupnow, countryinfo / countryinfonow, the online opencage / opencagenow subcommands, the geocode index-* subcommands for managing the local Geonames cities index, and the geocode cache-* subcommands for managing the on-disk OpenCage result cache.

Setting up the index

# 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 index

Old 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 with QSV_GEOCODE_INDEX_FILENAME) is always kept. Run qsv geocode index-reset to clean up an existing cache right away.

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).

Choosing a population floor

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.

index-load fixes in 23.0.1

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-load no longer rejects every index as invalid — including qsv's own published prebuilt. Both forms failed, and the command contradicted itself within a single run, printing Valid: /tmp/15000.rkyv and 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 that index-check uses, against the resolved path. The premature Valid: line is gone — it came from a helper that only checked the file's extension and existence, so it now reports Found 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 1000 downloaded to its bare argument as a relative path, dropping files named 1000 and 1000.rkyv into 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 stray 1000, 1000.rkyv, 15000 or 15000.rkyv files left behind in old working directories are safe to delete.
  • index-load installs 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.

Forward geocoding (suggest)

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.csv

Example: 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.csv

The %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

New in 24.0.0 (#4687):

  • --admin1 is 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, suggest fell back to the best match anywhere, so Inverness under US.FL came back as Inver Grove Heights, Minnesota. Small towns missing from the default index are the usual cause of a miss, and index-load 1000 finds more of them (choosing a population floor).
  • US territories work: US.PR, US.VI, US.GU, US.AS and US.MP. Geonames files them as countries of their own, so --admin1 US.PR used to find no Puerto Rico place at all (Ponce came back as Ponca City). An explicit --country US admits them too.
  • Mixed code lists infer every country, so --admin1 US.NY,US.PR needs no --country. Admin1 names still need --country.
  • 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.

Reverse geocoding (reverse)

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.csv

Location 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.csv

Census joins need the 5-digit county GEOID. us_county_fips_code is the 3-digit county part (003), unique only within a state — prefix it with us_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.

One-shot variants (suggestnow, reversenow, countryinfonow)

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 US

IP lookup (iplookup)

Needs the MaxMind GeoLite2-City.mmdb.

qsv geocode iplookup --new-column country ip_col logs.csv > logs_with_country.csv

Country info (countryinfo)

qsv geocode countryinfo country_code visitors.csv > with_country_info.csv
# Adds columns: name, capital, area, population, languages, currency, ...

Online geocoding with OpenCage (opencage, opencagenow)

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).

Managing the OpenCage cache (cache-*)

The opencage / opencagenow subcommands keep their results in a persistent on-disk cache that lives in {cache-dir}/geocode-opencage_v1 (default cache dir ~/.qsv-cache/). It is only populated by the OpenCage subcommands — the Geonames cities index is managed separately via index-*. Three subcommands manage this cache:

# wipe the entire OpenCage cache
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-info

cache-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, Recipe: Geographic Enrichment, Lookup Tables — for fallback when geocode misses.

geoconvert

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.geojson

Example: SHP → CSV (drops to tabular form)

qsv geoconvert nyc_boroughs.shp shp csv > nyc_boroughs.csv

Example: pick a file via dialog, then convert

qsv prompt -m 'Choose a GeoJSON file' -F geojson \
  | qsv geoconvert - geojson csv > result.csv

Example: 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.geojson

See also: /docs/help/geoconvert.md, geocode, Conversion & I/O.

See also

Home · Why qsv? · Tier legend

Quick links

Get Started

Command Reference

Cookbook

Tuning & Internals

Ecosystem

Reference

Legacy

Clone this wiki locally