Geo-location index support is a highlight of MongoDB, which is one of the reasons why foursquare, the world's most popular LBS service, chose MongoDB. We know that the usual database index structure is B + Tree. How to convert the geographic location into a form that can build B + Tree will be described below for you.
First assume that we divide the entire map that needs to be indexed into 16 × 16 squares, as shown below (the lower left corner is coordinate 0,0 and the upper right corner is coordinate 16,16):
MongoDB geolocation index implementation principle
Simple [x, y] data cannot be indexed, so when MongoDB indexes, it will calculate a hash value that can be used for indexing according to the coordinates of the corresponding field. This value is called geohash. Below we use the map The point with coordinates [4, 6] (the position of the red cross in the figure) is taken as an example.
Our first step is to divide the entire map into four blocks of equal size, as shown below:
MongoDB geolocation index implementation principle
After dividing into four blocks, we can define the values of these four blocks as follows (00 in the lower left, 01 in the upper left, 10 in the lower right, and 11 in the upper right):
01 11
00 10
So the geohash value of [4, 6] points is currently 00
Then cut each of the four small pieces as follows:
MongoDB geolocation index implementation principle
At this time, the point [4, 6] is located in the upper right area, and the value at the upper right is 11, so the geohash value of the point [4, 6] becomes: 0011
Continue to make two cuts:
MongoDB geolocation index implementation principle
MongoDB geolocation index implementation principle
Finally, the geohash value of [4, 6] points is: 00110100
In this way, we use this value for indexing, and the points with similar points on the map can be converted into geohash values with the same prefix.
We can see that the accuracy of this geohash value is proportional to the number of times the map was divided. The above example divides the map four times. By default, MongoDB performs 26 partitions. This value is controllable during indexing. The specific command to create a two-dimensional geographic index is as follows:
db.map.ensureIndex ({point: "2d"}, {min: 0, max: 16, bits: 4})
The bits parameter is divided several times, and the default is 26 times.