Geospatial

Geospatial indexes were introduced early on in MongoDB and the fact that FourSquare is one of the earliest customers and success stories for MongoDB (then 10gen Inc) is probably no coincidence.

There are three distinct types of geospatial index that we will explore in this chapter.

2d

A 2d geospatial index stores geospatial data as points on a two-dimensional plane. It is mostly kept for legacy reasons for coordinate pairs created before MongoDB 2.2 and in most cases should not be used with the latest versions.

2dSphere

A 2dSphere geospatial index supports queries calculating geometries in an earth-like plane. It is more accurate than the simplistic 2d index and can support both GeoJSON objects and coordinate pairs as input.

Its current version since MongoDB 3.2 is version 3. It is a sparse index by default, only indexing documents that have a 2dSphere field value.

Assuming that we have a location field in our books collection, tracking the home address of the main author of each book, we could create an index on this field like this:

> db.books.createIndex( { "location" : "2dsphere" } )

The location field needs to be a GeoJSON object, for example like this one:

location : { type: "Point", coordinates: [ 51.5876, 0.1643 ] }

A 2dSphere index can also be part of a compound index, as the first field or not.

> db.books.createIndex( { name: 1, location : "2dsphere" } )

geoHaystack

geoHaystack indexes are useful when we need to search geographical-based results in a small area. Like searching for a needle in a haystack, with a geoHaystack index we can define buckets of geolocation points and get back all the results that belong in this area.

Creating a geoHaystack index:

> db.books.createIndex( { "location" : "geoHaystack" ,
"name": 1 } ,
{ bucketSize: 2 } )

This will create buckets of documents within 2 units of latitude or longitude from each document.

Here, with the preceding example location:

location : { type: "Point", coordinates: [ 51.5876, 0.1643 ] }

Based on the bucketSize: 2, every document with location [49.5876..53.5876, -2.1643..2.1643] will belong in the same bucket as our location.

A document can appear in multiple buckets. If we want to use spherical geometry, 2dSphere is a better solution. geoHaystack indexes are sparse by default.

If we need to calculate the nearest document to our location and this is outside our bucketSize (that is, greater than 2 units of latitude/longitude in our example), queries will be inefficient and possible inaccurate. Use a 2dSphere index for such queries.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.104.250