Geo-index support is one of the highlights of MongoDB , which is one of the reasons why the world's most popular LBS service Foursquare choose MongoDB. We know that the usual database index structure is a B + Tree, and how to convert a geographic location into an b+tree form that you will describe below.
First, let's say we divide the entire map that needs to be indexed into 16x16 squares, such as (the lower-left corner is the coordinates 0,0 the upper-right corner is the coordinate 16,16):
The simple [x, y] data cannot be indexed, so when MongoDB builds the index, it calculates a hash value that can be used to do the index based on the coordinates of the corresponding field, which is called Geohash, and below we take the map coordinates as [4, 6] (the position of the Red fork in the figure) is an example.
Our first step is to divide the entire map into four blocks of equal size, such as:
After dividing into four blocks, we can define the values of the four blocks as follows (00 on the left, 01 on the left, 10 on the right and 11 on the right):
The Geohash value for this [4,6] point is now 00
Then cut each of the four small pieces, as follows:
At this point the [4,6] dot is in the upper right area and the value on the right is 11 so that the [4,6] point's Geohash value becomes: 0011
Continue to slice two times:
The resulting Geohash value for the [4,6] point is: 00110100
So we use this value to index, then the point near the map can be converted to the same prefix of the Geohash value.
As we can see, the accuracy of this geohash value is proportional to the number of times the map was divided, the above example divided the map four times. MongoDB, by default, is divided 26 times, and this value is controllable when the index is built. The command to establish a two-dimensional geographical location index is as follows:
Db.map.ensureIndex ({point: "2d"}, {min:0, max:16, bits:4})
The bits parameter is divided several times, the default is 26 times.
Http://blog.nosqlfan.com/html/1811.html