To rebuild a location database on Linux, you re-derive the stored geospatial structures from a trustworthy source of coordinates instead of patching the existing index. The core condition is that your original latitude/longitude records are intact and your toolchain exposes a rebuild or reindex operation; if those records were overwritten, "rebuilding" is really a data recovery job, not an indexing job.
That distinction matters because location databases wear several hats. A routing engine stores a graph of nodes and edges. A geocoder stores normalized place names tied to points or bounding boxes. A spatial extension such as PostGIS stores geometry plus a spatial index. Each has its own rebuild path, and each fails differently when interrupted. This guide covers the common Linux workflows: identifying what "location database" you actually have, taking a safe snapshot, rebuilding spatial indexes, regenerating derived tiles and address points, and verifying that the result matches reality.
What "Rebuilding" Means for Different Location Databases
A location database is any dataset where position is a first-class field: points of interest, addresses, road networks, administrative boundaries, or GPS traces. The word "rebuild" can refer to three quite different operations, and mixing them up is the most common source of wasted hours.
The first is an index rebuild. The underlying rows stay put, but the search structures—R-trees, GiST indexes, k-d trees, geohash columns—are dropped and regenerated. This is fast, low-risk, and fixes slow or inaccurate spatial queries caused by corrupted or stale indexes.
The second is a derived-data regeneration. Here the source rows are untouched, but computed artifacts are recreated: routing graphs compiled from OpenStreetMap extracts, vector tiles from a planet file, address points interpolated from street segments, or geohash columns recomputed from coordinates. This takes hours to days at national scale and is where disk space and memory bite.
The third is a full reload, where the location records themselves are re-imported from an upstream dump or backup. This is the only option when coordinates were corrupted by a bad migration or a faulty bulk update.
Before touching anything, classify your system. Run a quick inventory: which service owns the data (PostgreSQL with PostGIS, SQLite with SpatiaLite, a Nominatim instance, an OSRM or Valhalla routing server, Elasticsearch with geo fields, or a custom store), where the files live, and whether a rebuild command already exists. Most mature geospatial tools ship an explicit rebuild step, and using it beats hand-rolling SQL.
Prerequisites and a Pre-Rebuild Safety Check
You need root or service-account access, enough free disk to hold a second copy of the database plus its indexes (a practical rule is 1.5 to 2 times the current data size when rebuilding indexes, more for a full reload of a planet-scale dataset), and a maintenance window during which writes can pause or be queued.
Start with these reversible checks before any destructive action:
1: Confirm free space with df -h on the volume holding the database and its temporary directory. Index builds spill to disk. 2: Confirm memory headroom. A spatial index build for a large table can use a substantial fraction of RAM; check with free -h and compare against the tool's documented maintenance_work_mem-style setting. 3: Confirm the service is healthy and note its version: for PostgreSQL, SELECT version(); for SpatiaLite, SELECT spatialite_version(); for a routing engine, its binary's --version output. 4: Verify your source of truth. Count rows and spot-check a handful of known coordinates before you change anything, so you have a baseline to compare against afterward. 5: Take a snapshot. A logical dump (pg_dump for PostgreSQL, .dump for SQLite) or a filesystem snapshot is faster to restore than re-importing from upstream. Test that the dump restores into a scratch database. 6: Stop writes. Put the service in read-only mode or stop it. Rebuilding indexes while writes continue can produce inconsistent structures and lock contention.
If the database is part of a live routing or geocoding service, this is the point to announce downtime. A rebuild that finishes in twenty minutes on a test extract can run for many hours on production data, so measure on a copy first.
Rebuilding Spatial Indexes in PostgreSQL and PostGIS
PostGIS is the most common Linux-hosted location store, and its rebuild path is well-defined. The spatial index is a GiST index over a geometry or geography column; rebuilding means recreating that index, not re-importing rows.
First, find the indexes tied to your geometry columns. Query the catalog for indexes on the table, then inspect their definitions to identify the spatial ones. A spatial index definition names the GiST access method and the geometry column.
Then rebuild. The simplest, safest sequence is to drop the spatial index and recreate it, which forces a full build from the table's current rows. Do this inside a transaction where the tooling allows, or with the service paused. For a routine refresh without dropping, REINDEX INDEX rebuilds in place; PostgreSQL's REINDEX CONCURRENTLY variant avoids blocking reads but takes longer and cannot run inside a transaction block.
Two practical cautions. First, a freshly built index is only as good as the geometry it indexes: if rows contain invalid polygons or swapped latitude/longitude values, the index will faithfully encode the error. Validate geometries before rebuilding and fix or quarantine invalid rows. Second, set an appropriate maintenance memory budget for the session so the build doesn't thrash; the exact setting name and sensible value depend on your PostgreSQL version, so check the documentation for that version rather than copying a number from an old blog post.
For a table whose spatial column is derived—say, a point computed from separate latitude and longitude columns—the rebuild has two steps: recompute the geometry column from the source coordinates, then rebuild the index. Treat the recomputation as a data change and back up first.
Success check: after the rebuild, run a small bounding-box query around a known landmark and confirm it returns the expected nearby rows, and confirm the query planner is using the spatial index rather than a sequential scan. If the planner ignores the index, statistics may be stale; updating table statistics is the next reversible step.
Rebuilding SQLite and SpatiaLite Location Stores
SQLite is common in embedded and mobile-adjacent location services, and SpatiaLite adds spatial types and R-tree indexes. The rebuild mechanics are simpler and more manual than PostGIS.
Here the spatial index is a separate virtual table, typically named after the indexed table with an rtree prefix. Rebuilding means dropping that virtual table and recreating it, then repopulating it from the base table's geometry column. The exact function names for creating and populating the R-tree are SpatiaLite-specific, so confirm them against the version you have installed before running anything.
A workable order:
1: Open the database read-write with the service stopped. 2: Confirm the R-tree virtual table exists and note its name. 3: Drop the virtual table. 4: Recreate it over the same geometry column. 5: Repopulate it from the base rows. 6: Run an integrity check on the database file.
If the geometry column itself is stale—for example, after a bulk coordinate correction—recompute geometry from the source latitude/longitude fields first, then rebuild the R-tree.
A realistic failure mode: a partially populated R-tree after an interrupted import leaves spatial queries returning wrong or missing results while non-spatial queries look fine. That symptom—correct data, wrong map results—points at the index, not the rows, and a clean rebuild is the fix.
Regenerating Routing Graphs and Geocoding Indexes
Routing engines and geocoders are the heaviest rebuild targets because they compile large derived structures from map extracts.
For a routing engine built on OpenStreetMap data, the pipeline is typically: obtain an extract for your region, run the engine's preprocessing step to build the graph, then swap the new graph directory into place and restart the service. The preprocessing step is CPU- and memory-intensive and can take from minutes for a city extract to many hours for a continent. The critical discipline is to build into a separate directory, verify the new graph with a few known routes, and only then replace the live one. Never preprocess directly over a running graph.
For a geocoder such as a Nominatim-style service, the rebuild involves re-importing or updating from the source extract and then regenerating search indexes and any address interpolation data. National-scale imports are measured in hours to days and need substantial temporary disk. The safe pattern is the same: build a fresh database or a fresh index set, validate it against a list of known addresses, then cut over.
One reusable technique across all of these: keep the last known-good derived directory. A rebuild that produces a subtly wrong graph—missing a motorway link, misplacing a boundary—is worse than an old graph, because it fails quietly. Version your derived artifacts by date so rollback is a directory rename, not a re-import.
Verifying the Rebuilt Database
Verification is where a rebuild becomes trustworthy. Do it before you reopen writes.
Use three layers of checks. First, structural: confirm row counts match the pre-rebuild baseline, confirm indexes exist and are valid, and run the database's own integrity or consistency check. Second, functional: run a fixed set of queries with known expected answers—nearest-neighbor searches around landmarks, bounding-box counts for a city, a handful of address lookups. Compare results to the pre-rebuild baseline; identical results for spatial queries are the strongest signal that the index is sound. Third, performance: time a representative spatial query and confirm it is in the expected range rather than orders of magnitude slower, which would indicate the planner is not using the new index.
A simple, reproducible spot check for a point database: pick three coordinates you know well, query the nearest five records to each, and confirm the returned distances and identities look correct. For a routing graph, compute two or three routes you know and confirm distance and geometry match expectations. For a geocoder, resolve several addresses and compare against the previous output.
If functional checks pass but performance is poor, the index is likely fine and the problem is statistics or configuration—both cheaper to fix than a rebuild. If functional checks fail, stop and investigate before reopening the service; a wrong location database is a silent outage.
Common Failures, Causes, and Reversible Fixes
The most frequent rebuild problems have recognizable symptoms, and the first response should always be the least destructive one.
Out of disk during an index build. This aborts the build and can leave a partially built index. Fix: free space, drop the incomplete index, and retry. Prevent it by sizing free space against the data size before starting.
Lock timeouts and blocked writes. Long index builds hold locks. Fix: use the concurrent rebuild variant where available, or schedule the rebuild in a maintenance window with writes paused. Don't kill a build mid-flight unless you're prepared to drop and restart it.
Swapped latitude and longitude. A rebuild won't fix this, and the index will happily encode it. Symptom: points appear in the wrong hemisphere or offshore. Fix: correct the source columns first, then recompute geometry and rebuild.
Invalid or self-intersecting polygons. These can fail index creation or produce unreliable spatial queries. Fix: detect and repair geometries before rebuilding; quarantine rows you cannot repair.
Stale statistics after rebuild. Symptom: the planner avoids the new index. Fix: update statistics, then re-time the query.
Interrupted import leaving half a dataset. Symptom: spatial queries miss whole regions while counts look plausible at first glance. Fix: compare against the source extract's record counts and reload if they diverge.
Stop condition: if integrity checks or functional checks fail after a clean rebuild from a verified backup, and the cause is not an obvious configuration or geometry problem, stop making changes and involve the database or geospatial platform's support channel. Repeated rebuilds on a database with unexplained corruption risk making the damage harder to diagnose.
Practical Notes on Time, Space, and Maintenance
Rebuilds are a maintenance task, not a one-off. Two habits pay off.
First, treat derived geospatial data as disposable and versioned. Keep the source coordinates as the canonical record and be able to regenerate indexes, graphs, and tiles from it at will. This makes rebuilds routine instead of scary.
Second, measure on a copy. Extract a representative slice of your region, run the full rebuild against it, and record wall-clock time, peak memory, and disk use. Scale estimates are rough—cost grows faster than linearly for index builds and graph compilation on large datasets—so use the copy to set a realistic window rather than extrapolating from a city to a continent.
Finally, schedule rebuilds after bulk data imports and after coordinate corrections, and before major releases. A location database with a stale index is not obviously broken; it just quietly returns the wrong nearby places, which is the hardest kind of bug to notice and the easiest to prevent.