Database Reference
In-Depth Information
appendix E
Spatial indexing
With the proliferation of smart mobile devices, the demand for location-based services
has been increasing steadily. To build these location-dependent applications requires
a database capable of indexing and querying spatial data. This feature was added to
the MongoDB road map fairly early on, and MongoDB's spatial indexing, though not
as fully featured as, say, PostGIS, nevertheless now powers the location queries for a
number of popular sites. 1
As the name implies, spatial indexes are optimized for data representing locations.
In the case of MongoDB, this data is typically represented as longitude and latitude on
the geographic coordinate system. A spatial index on the data can then permit que-
ries based on a user's location. For example, you might have a collection containing
menu data and coordinates for every restaurant in New York City. With an index on
those restaurant locations, you can query the database for the closest restaurant to the
Brooklyn Bridge serving caviar.
What's more, the indexer is generic enough to work outside the terrestrial. This
means that you can even use it to index locations on two-dimensional coordinate
planes or on the planet Mars. 2 Regardless of your use case, spatial indexes are rela-
tively easy to build and query on. Here I'll describe how to build these indexes, the
range of queries possible, and a few internal design specs.
E.1
Spatial indexing basics
We'll use a US ZIP code database to demonstrate MongoDB's spatial indexes. The data
is available at http://mng.bz/dOpd . When you unzip the archive, you'll get a JSON
file that you can import using mongoimport , like so:
$ mongoimport -d geo -c zips zips.json
Let's first look at a ZIP code document. If you followed the import instructions, you
should be able to fetch a document like so:
> use geo
1
The most prominent of these is Foursquare ( http://foursquare.com ). You can learn more about Four-
square's MongoDB usage at http://mng.bz/rh4n .
2
A great example of the former is WordSquared ( http://wordsquared.com ) , a Scrabble-like game that uses
MongoDB's spatial indexing for queries against the tiles on its game board.
274
 
Search WWH ::




Custom Search