Practice this topic in a realistic system design interview
Spatial search gets harder when the objects are not just points. Restaurants may be points, but delivery zones are polygons, roads are lines, and buildings are shapes that cover an area. Checking every shape for every query does not scale.
An R-tree speeds this up by wrapping each shape in a rectangle and grouping nearby rectangles into larger ones. A search can then skip whole groups that are nowhere near the query.
In this chapter, we'll learn what an R-tree is, how it groups shapes into nested bounding rectangles, how it answers spatial queries, and why it is the index behind most spatial databases.
Suppose you're building a food delivery app. Each restaurant has a delivery zone, which defines the area where it can deliver orders.
These zones are not necessarily circles. They can be irregular polygons that follow streets, rivers, and neighborhood boundaries.
When a customer opens the app, you need to figure out which restaurants can deliver to their location. In other words, which delivery zones contain the customer's location?
To answer this, we need to check whether the customer's location falls inside each polygon. This involves some geometric calculations, especially when polygons have hundreds of edges.
Now imagine you have 1 million restaurants, each with its own delivery zone. Checking the customer's location against every polygon for every request would be far too slow:
What we need is a way to quickly eliminate delivery zones that are nowhere near the customer, so we only check the ones that might actually contain their location.
Spatial indexing structures like Geohash and quadtrees work well for points. Each point falls into exactly one cell, so it's relatively easy to organize and search for.
But shapes are more complicated. A restaurant's delivery zone can cover a large area and span multiple cells.
So instead of dividing space into fixed regions, we need a structure that can efficiently organize objects based on their size and shape.