Mongodb Guide (translation) (20)-developer zone-index (4) Geographic Information Index

Source: Internet
Author: User

MongoDB supports two-dimensional geographic information indexing. It is designed for location-based queries in the mind, such as "finding N places closest to my location ". It can also efficiently process additional query conditions, such as "finding N museums closest to my location ".

To use this index, you need to set a field in your object. This field can be a child object or an array with the first two elements x and y coordinates (or y, x-you only need to ensure consistency. To ensure consistency, we recommend that you use a sorted dictionary/hashes in your client code .).

Some examples:

{ loc : [ 50 , 30 ] } //SUGGESTED OPTION
{ loc : { x : 50 , y : 30 } }
{ loc : { foo : 50 , y : 30 } }
{ loc : { lon : 40.739037, lat: 73.992964 } }
Copy code

Create this index

db.places.ensureIndex( { loc : "2d" } )

By default, the index assumes that you are in the index longitude/dimension, and the value range is [-180,180].

If you are indexing other things, you can specify some options:

db.places.ensureIndex( { loc : "2d" } , { min : -500 , max : 500 } )

This will store the value range from-500 to 500 for index expansion. Currently, Geographic Information Boundary Search is restricted within rectangles and circles without boundaries. You cannot insert values beyond the boundary [min, max. For example,

Using the above Code, a vertex (-500,500) cannot be inserted and an error is triggered (however, a vertex (-500,499) is acceptable ).

db.places.ensureIndex( { loc : "2d" } , { bits : 26 } )

The bits parameter sets the accuracy of the 2D geo-hash Value and the minimum record of the storage location. By default, the precision is set to 26 BITs, which is roughly equivalent to the 1 step for positioning (longitude, latitude). The default boundary is (-180,180 ). To create an index for a space with a larger boundary, you can increase the number of digits to the maximum value of 32.

Currently, you can create only one Geographic Information index for each set.

The Fuzzy size array syntax can only be used in versions not lower than V1.9. The nested fields that can be referenced in "2d" in "foo. bak" are similar:

{ foo : [ { bar : [ ... ] } ] }

This restriction exists even if not every document has multiple locations and the array size is 1. In the old version, you need to embed the embedded location into a non-array:

{ foo : { bar : [ ... ] } }

Query

This index can be used for exact query:

db.places.find( { loc : [50,50] } )

Of course, this is not very interesting. More importantly, you can query the points near a certain point without exact match:

db.places.find( { loc : { $near : [50,50] } } )

The preceding query finds the closest vertex (50, 50) and returns the result after sorting by distance (No sort parameter needs to be added here ). Use Limit () to specify the maximum number of returned results (100 returned by default ):

db.places.find( { loc : { $near : [50,50] } } ).limit(20)

You can also add a maximum distance parameter to $ near:

db.places.find( { loc : { $near : [50,50] , $maxDistance : 5 } } ).limit(20)

The distance in all geospatial queries is the same as the unit in the coordinate system of the document (except for the spherical query discussed later ). For example, if the size of the area you index is [300,300), it indicates a 300*300 square meter location, and you have two documents in () and, represents the points in (x, y), and you can query these locations $ near: [], $ maxdistance: 10. the distance unit is the same as that of your coordinate system, so this query finds the target point within 10 meters of the point.

Joint Index

The MongoDB geographic information index supports optional slave keys. If you frequently query the address and other attributes at the same time, you can add other attributes to the index. Other attributes can be used as index annotations to make filtering faster. For example:

db.places.ensureIndex( { location : "2d" , category : 1 } );
db.places.find( { location : { $near : [50,50] }, category : 'coffee' } );
Copy code

Geonear command

Although the find () function is usually the first, MongoDB provides a geonear command to execute similar functions. The geonear command can return the distance between each point and the query point in the query results, as well as some fault diagnosis information.

Valid options include "near", "num", "maxdistance", "distancemultiplier", and "query ".

> db.runCommand( { geoNear : "places" , near : [50,50], num : 10 } );
> db.runCommand({geoNear:"asdf", near:[50,50]})
{
"ns" : "test.places",
"near" : "1100110000001111110000001111110000001111110000001111",
"results" : [
{
"dis" : 69.29646421910687,
"obj" : {
"_id" : ObjectId("4b8bd6b93b83c574d8760280"),
"y" : [
1,
1
],
"category" : "Coffee"
}
},
{
"dis" : 69.29646421910687,
"obj" : {
"_id" : ObjectId("4b8bd6b03b83c574d876027f"),
"y" : [
1,
1
]
}
}
],
"stats" : {
"time" : 0,
"btreelocs" : 1,
"btreelocs" : 1,
"nscanned" : 2,
"nscanned" : 2,
"objectsLoaded" : 2,
"objectsLoaded" : 2,
"avgDistance" : 69.29646421910687
},
"ok" : 1
}
Copy code

The preceding command returns 10 points closest to (50, 50. (The LOC field is automatically determined when the 2D index is checked on the Set)

If you need to add a filter, you can do this:

> db.runCommand( { geoNear : "places" , near : [ 50 , 50 ], num : 10,
... query : { type : "museum" } } );
Copy code

Query can be any common Mongo query.
Article transferred from: http://www.cnblogs.com/xinghebuluo/archive/2012/01/18/2308753.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.