Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 20 min · revision 1

Indexing location: geohash, quadtrees and S2 cells

Answer "what is near me?" with a spatial index: encode geohashes and search a cell with its neighbours, let a quadtree adapt to density, cover regions with S2 cells, compare H3 hexagons, and finish with an exact distance filter.

Contentsand lesson path

On this page

  1. Why it matters
  2. Geohash: a cell ID you can sort
  3. Quadtrees: cells that follow the data
  4. S2 and H3: cells for the whole sphere
  5. Check your understanding
  6. Apply it
  7. Review prompt

Lessons of Search & Indexing Services

  1. Inverted indexes, analyzers and scoring Concept · 25 min
  2. Keeping search in sync: CDC, reindexing and aliases Concept · 20 min
  3. Shards, replicas and scatter-gather queries Concept · 20 min
  4. Designing typeahead under 100 ms Worked example · 25 min
  5. Indexing location: geohash, quadtrees and S2 cells Concept · 20 min
  6. Search design check Knowledge check · 8 questions

What you will learn

  • Choose a geospatial index (geohash, quadtree, S2 cells) for proximity queries.

01. Why it matters

Many features ask a proximity query: the shops within 1 km, the five nearest drivers, the delivery zone that contains this address. An ordinary index does not help much. An index on latitude finds every point in a thin band that runs around the whole planet, and an index on longitude finds a band from pole to pole; intersecting two large bands is slow.

Spatial indexes group points that are close on the map, so that a query reads a few small groups instead of the whole table. There are two families. Grids give every point a cell ID and turn a 2D question into a few 1D key lookups: geohash, S2 and H3 work this way. Trees split space where the data is, as quadtrees and R-trees do. Both return candidates, which then go through an exact distance test, the same two-pass approach that PostGIS documents for its index.

02. Geohash: a cell ID you can sort

A geohash halves the longitude range and records 1 if the point is in the upper half and 0 if not, then does the same for latitude, and repeats. Every 5 bits become one character from a 32-character alphabet. Each extra character narrows the cell, and every point inside a cell has that cell's geohash as a prefix. Because cells are prefixes, a sorted index such as a B-tree finds all points in a cell with one range scan over keys that start with the prefix.

The script implements encoding, cell bounds and the block of a cell plus its 8 neighbours, then runs a 1 km search over 5,000 random shops in Amsterdam. The first line checks the encoder against the two examples on the Geohash Wikipedia page. Distances use the haversine formula on a sphere, an approximation that Redis documents as wrong by up to 0.5% in the worst case.

Python 3.12 · geohash_demo.py
"""Geohash encoding, cell sizes, neighbours and a radius search.
Python 3.12, standard library only. Distances assume a spherical Earth."""
import math
import random

BASE32 = '0123456789bcdefghjkmnpqrstuvwxyz'  # no a, i, l, o
EARTH_KM = 6371.0088  # mean radius


def encode(lat: float, lon: float, precision: int) -> str:
    """Halve the longitude and latitude ranges in turn; 5 bits make a character."""
    lat_rng, lon_rng = [-90.0, 90.0], [-180.0, 180.0]
    out, value, count, even = [], 0, 0, True
    while len(out) < precision:
        rng, x = (lon_rng, lon) if even else (lat_rng, lat)
        bit = int(x >= (rng[0] + rng[1]) / 2)
        rng[1 - bit] = (rng[0] + rng[1]) / 2  # keep the half that holds x
        value, count, even = value * 2 + bit, count + 1, not even
        if count == 5:
            out.append(BASE32[value])
            value, count = 0, 0
    return ''.join(out)


def bounds(cell: str) -> tuple[float, float, float, float]:
    """South, north, west and east edges of a cell."""
    lat_rng, lon_rng, even = [-90.0, 90.0], [-180.0, 180.0], True
    for char in cell:
        n = BASE32.index(char)
        for shift in range(4, -1, -1):
            rng = lon_rng if even else lat_rng
            rng[1 - (n >> shift & 1)] = (rng[0] + rng[1]) / 2
            even = not even
    return lat_rng[0], lat_rng[1], lon_rng[0], lon_rng[1]


def distance_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    """Haversine great-circle distance."""
    p1, p2 = math.radians(lat1), math.radians(lat2)
    dp, dl = p2 - p1, math.radians(lon2 - lon1)
    h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
    return 2 * EARTH_KM * math.asin(math.sqrt(h))


def size_km(cell: str) -> tuple[float, float]:
    s, n, w, e = bounds(cell)
    mid = (s + n) / 2
    return distance_km(mid, w, mid, e), distance_km(s, w, n, w)


def block(cell: str) -> list[str]:
    """The cell and its 8 neighbours: step one cell size from its centre."""
    s, n, w, e = bounds(cell)
    cells = []
    for dy in (1, 0, -1):
        for dx in (-1, 0, 1):
            lat = (s + n) / 2 + dy * (n - s)
            lon = ((w + e) / 2 + dx * (e - w) + 180) % 360 - 180  # wrap at 180°
            if -90 < lat < 90:
                cells.append(encode(lat, lon, len(cell)))
    return cells


print('check:', encode(42.605, -5.603, 5), encode(57.64911, 10.40744, 11))
print('precision  width x height at 0°N   at 60°N')
for p in range(4, 8):
    eq, north = size_km(encode(0.1, 10.0, p)), size_km(encode(60.1, 10.0, p))
    print(f'{p:>9}  {eq[0]:8.3f} x {eq[1]:<8.3f} {north[0]:8.3f} x {north[1]:.3f} km')

user = (52.3731, 4.8924)  # central Amsterdam
cell = encode(*user, 6)
print('user cell', cell, '-> block', ' '.join(block(cell)))

rng = random.Random(7)
shops = [(52.3731 + rng.uniform(-0.1, 0.1), 4.8924 + rng.uniform(-0.15, 0.15))
         for _ in range(5_000)]
RADIUS = 1.0
for p in (6, 5):
    w, h = size_km(encode(*user, p))
    cells = set(block(encode(*user, p)))
    candidates = [s for s in shops if encode(*s, p) in cells]
    near = [s for s in candidates if distance_km(*user, *s) <= RADIUS]
    print(f'precision {p} ({w:.2f} x {h:.2f} km): 9 cells hold {len(candidates)} shops,'
          f' {len(near)} within {RADIUS} km')
print('all shops within 1 km:', sum(distance_km(*user, *s) <= RADIUS for s in shops))
Expected output (python3 geohash_demo.py)
check: ezs42 u4pruydqqvj
precision  width x height at 0°N   at 60°N
        4    39.092 x 19.546     19.529 x 19.546 km
        5     4.886 x 4.887       2.436 x 4.887 km
        6     1.222 x 0.611       0.609 x 0.611 km
        7     0.153 x 0.153       0.076 x 0.153 km
user cell u173zq -> block u173zp u173zr u173zx u173zn u173zq u173zw u173zj u173zm u173zt
precision 6 (0.75 x 0.61 km): 9 cells hold 50 shops, 42 within 1.0 km
precision 5 (2.98 x 4.89 km): 9 cells hold 1407 shops, 44 within 1.0 km
all shops within 1 km: 44

Three lessons come out of these numbers:

  • Cells shrink towards the poles. A precision-5 cell is 4.9 km wide at the equator but 2.4 km wide at 60°N, because lines of longitude converge. The same precision covers half the ground in Oslo that it covers in Singapore.
  • Search the block, not the cell. A shop 50 m away can sit in the next cell, and neighbouring cells may share no prefix at all. Redis documents the same approach for GEOSEARCH: check the 1 + 8 areas around the point, then discard the members outside the shape.
  • The cells must be at least as large as the radius. At precision 6 the cells here are 0.75 by 0.61 km, smaller than the 1 km radius, so the block reaches less than 1 km in some directions and misses 2 of the 44 shops. At precision 5 the block covers the circle, but it returns 1,407 candidates for 44 real hits. The exact distance filter is not optional: it removes 97% of the candidates.

So pick the finest precision whose cells are at least as wide and as tall as the radius at that latitude. If the block still returns too many candidates, use a covering of smaller cells (S2 below) or a tree. If you use Redis, note that GEORADIUS has been deprecated since Redis 6.2; new code should use GEOSEARCH with BYRADIUS.

03. Quadtrees: cells that follow the data

A geohash cell has the same size whether it holds no shops or ten thousand. A quadtree can adapt instead. Quadtrees go back to Finkel and Bentley (1974), whose point quadtree stores one point in each node and splits the space at that point. The variant used here, a bucket point-region (PR) quadtree, starts with one square and splits a square into four equal squares only when it holds more than a set number of points. The script fills a flat 64 by 64 km map with a dense city and a sparse countryside, then queries a 2 by 2 km box in the centre.

Python 3.12 · quadtree_demo.py
"""A bucket point-region (PR) quadtree: a square splits into four equal squares
when it holds more than CAPACITY points.
Python 3.12, standard library only. Coordinates are km on a flat 64 x 64 km map."""
import random

CAPACITY = 32


class Node:
    def __init__(self, x: float, y: float, size: float, depth: int = 0):
        self.x, self.y, self.size, self.depth = x, y, size, depth
        self.points, self.children = [], None

    def insert(self, p: tuple[float, float]) -> None:
        if self.children:
            half = self.size / 2
            i = (p[0] >= self.x + half) + 2 * (p[1] >= self.y + half)
            return self.children[i].insert(p)
        self.points.append(p)
        if len(self.points) > CAPACITY and self.size > 0.01:
            half = self.size / 2
            self.children = [Node(self.x + dx * half, self.y + dy * half, half,
                                  self.depth + 1) for dy in (0, 1) for dx in (0, 1)]
            for q in self.points:
                self.insert(q)
            self.points = []

    def leaves(self):
        if not self.children:
            yield self
        else:
            for child in self.children:
                yield from child.leaves()

    def query(self, x0, y0, x1, y1, seen: list[int]) -> list:
        """Points inside a rectangle; seen[0] counts the points examined."""
        outside = x1 < self.x or x0 > self.x + self.size
        if outside or y1 < self.y or y0 > self.y + self.size:
            return []
        if self.children:
            return [p for c in self.children for p in c.query(x0, y0, x1, y1, seen)]
        seen[0] += len(self.points)
        return [p for p in self.points if x0 <= p[0] <= x1 and y0 <= p[1] <= y1]


rng = random.Random(11)
city = [(rng.gauss(20, 1.5), rng.gauss(20, 1.5)) for _ in range(9_000)]
rural = [(rng.uniform(0, 64), rng.uniform(0, 64)) for _ in range(1_000)]
root = Node(0.0, 0.0, 64.0)
inside = [p for p in city + rural if 0 <= p[0] < 64 and 0 <= p[1] < 64]
for p in inside:
    root.insert(p)

leaves = list(root.leaves())
print(f'{len(inside)} points, {len(leaves)} leaves,'
      f' deepest at depth {max(f.depth for f in leaves)}')
for name, (x, y) in {'city centre': (20.0, 20.0), 'countryside': (55.0, 55.0)}.items():
    leaf = next(f for f in leaves
                if f.x <= x < f.x + f.size and f.y <= y < f.y + f.size)
    print(f'{name:<12} leaf is {leaf.size:6.3f} km wide at depth {leaf.depth},'
          f' {len(leaf.points)} points')
seen = [0]
found = root.query(19.0, 19.0, 21.0, 21.0, seen)
print(f'2 x 2 km box in the centre: {len(found)} points found, {seen[0]} examined')
Expected output (python3 quadtree_demo.py)
10000 points, 676 leaves, deepest at depth 9
city centre  leaf is  0.125 km wide at depth 9, 12 points
countryside  leaf is  8.000 km wide at depth 3, 14 points
2 x 2 km box in the centre: 2215 points found, 3086 examined

The leaf in the city centre is 125 m wide at depth 9, while the countryside leaf is 8 km wide at depth 3, and both hold a similar number of points. The box query examined 3,086 of the 10,000 points to return 2,215, because it visited only the leaves that touch the box.

The price is in updates and distribution. Points that move, such as drivers, must be removed and reinserted, and leaves split and merge as they go. The cells depend on the data, so two servers with different data build different trees, and a tree is harder to split across machines or store in a key-value database than a cell ID. Quadtrees suit in-memory indexes of points with very uneven density. PostGIS uses a related tree, the R-tree, which groups the bounding boxes of shapes rather than points.

04. S2 and H3: cells for the whole sphere

S2, an open-source geometry library from Google, projects the sphere onto the six faces of a cube and divides each face like a quadtree, from level 0 to level 30, where a leaf cell is about 1 cm across. Cells are numbered along a Hilbert curve, a path that visits every cell and rarely jumps far, so cells that are close on the map usually have close 64-bit IDs. Two properties matter for design. First, cells of one level stay similar in size: at deep levels the largest is about 2.1 times the smallest anywhere on Earth, whereas a geohash cell at 60°N already has half the area of one at the equator. Second, S2 approximates any region with a covering, a short list of cells at mixed levels, and each cell is a contiguous range of leaf IDs. A radius query becomes a few range scans in any sorted store.

The size of a covering is a trade-off. The S2 documentation measured, over 100,000 random circles, that a covering limited to 8 cells has a median area about 1.98 times the circle, and one with 20 cells about 1.42 times. More cells mean fewer false candidates to filter but more ranges to read.

H3, from Uber, uses hexagons at 16 resolutions (0 to 15). A hexagon has 6 neighbours, all at the same distance from its centre, while a square has 8 neighbours at two different distances. That makes H3 convenient for movement and for counting things per area, such as demand per cell for surge pricing. Two caveats: every resolution contains exactly 12 pentagons, and a hexagon's seven children only approximately fill their parent, so exact boundaries need a point-in-polygon check.

Choosing a geospatial index: a starting point, not a rule
need                                         first choice
points in a key-value store, even density    geohash keys, 9-cell block, filter
very uneven density, in memory, k-nearest     PR quadtree (or an R-tree library)
global data, uniform cells, region coverings  S2 cell IDs as sorted keys
counting per area, movement between cells     H3 cells at one resolution
already on PostgreSQL, OpenSearch or Redis    PostGIS GiST, geo_point, GEOSEARCH

Start from the last row: the database you already run probably has a tested geospatial index, and building your own only pays off when its limits show up in measurements. Whatever you choose, the cells or tree nodes only produce candidates. For a proximity query, the answer comes from an exact distance test and a sort. Location is also personal data: keep exact positions only as long as the feature needs them, and store a coarse cell ID instead when an area is enough, for example in analytics. Moving objects add their own problems, such as stale positions and hot cells, which Ride-hailing design covers.

05. Check your understanding

Practice check · 3 questions

Cells, candidates and coverings

Three questions on candidate filtering, k-nearest searches and S2 coverings.

Q1. A service returns every shop in the 9 geohash cells around a user as "within 1 km". At the chosen precision, cells are about 5 km tall and 3 km wide. What is wrong with the results?
Q2. To find the 5 nearest drivers, a service searches the 9-cell block around a rider, with cells about 600 m in both directions. It finds exactly 5 drivers, the farthest 900 m away. Can it return them?
Q3. An S2 covering of a 2 km delivery radius can be limited to 4 cells or to 20 cells. What does choosing the 20-cell covering trade?
Practice only: not graded, not saved, not evidence.

06. Apply it

Add a "pick up in a store near me" filter to the product search design of this skill:

  1. Estimate the number of stores and how unevenly they are spread, and write down the radius users choose.
  2. Pick a geohash precision for that radius at your most northern and most southern store, using size_km from the script.
  3. Change geohash_demo.py to return the 5 nearest stores, widening the block until the fifth distance is covered.
  4. Decide whether your search engine's own geo field would serve instead, and what you would measure to decide.

07. Review prompt

Without looking back, explain: how a geohash is built and why a prefix is a cell; why a search uses a block of 9 cells and how to choose the precision; how a quadtree adapts to density and what it costs for moving points; what makes S2 cells and coverings useful; what H3 hexagons offer and their two caveats; and why every method ends with an exact distance filter.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check