Developer Zone-Index (iv) Geographical information index

Source: Internet
Author: User

MongoDB supports 2-D geo-information indexing. It is designed to carry out location-based queries in the mind, such as "Finding n places nearest to my location." It can also efficiently handle additional query conditions, such as "Finding n museums nearest to my location".

To be able to use this index, you need to set a field in your object that is either a child object or an array of the first two elements x,y coordinates (or y,x-as long as it is consistent; for consistency, it is recommended that you use a dictionary/hashes in your client code that keeps the sort. )。

Some examples:

The code is as follows Copy Code

{loc: [m]}//suggested OPTION
{loc: {x:50, y:30}}
{loc: {foo:50, y:30}}
{loc: {lon:40.739037, lat:73.992964}}


Create the Index

The code is as follows Copy Code

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


By default, this index assumes that you are indexing the longitude/dimension, and that the range of these values is [-180,180].

If you are indexing something else, you can specify some options:

The code is as follows Copy Code

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


This will store a value of 500 through 500 for index expansion. The Geographic information boundary search is currently restricted beyond the bounds of rectangles and circles. You cannot insert a value other than the boundary [Min,max]. For example

Using the above code, point (-500,500) cannot be inserted and will trigger an error (however, the point (-500,499) is OK).

The code is as follows Copy Code

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


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

Currently, you can only create a geographic information index for each collection.

The fuzzy size array syntax can only be used in versions that are not less than V1.9, and "2d" in "Foo.bak" can refer to an inline field similar to the following:

The code is as follows Copy Code

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


This restriction persists even if not every document has multiple locations and the array size is 1. In older versions, you need to embed embedded positions in a non-array:

The code is as follows Copy Code

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


Inquire

This index can be used for exact queries:

The code is as follows Copy Code

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

Of course, this is not very interesting. It is more important to query for points near a point and do not need an exact match:

The code is as follows Copy Code

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

The above query looks for the nearest point from (50,50) and returns sorted by distance (there is no need to increase the sorting parameters). Use limit () to specify the maximum number of returns (the default returns 100):

The code is as follows Copy Code

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


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

The code is as follows Copy Code

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


The distances in all geospatial queries are the same as units in the document coordinate system (except for the spherical query that is discussed next). For example, if you index a region size of [300,300], representing a 300*300 square meter lot, and you have two documents (10,20) and (10,30) that represent the points at (x,y), you can also query these location points $near: [10,20],$ Maxdistance:10. The distance unit is the same as your coordinate system, so this query looks for target points within 10 meters of the point.

Federated Index

The MongoDB Geographic Information index supports an optional from key. If you frequently query for addresses and other attributes, you can add additional attributes to the index. Other attributes, as annotations to the index, allow filtering to execute faster. For example:

The code is as follows Copy Code

Db.places.ensureIndex ({location: "2d", category:1});
Db.places.find ({location: {$near: [50,50]}, Category: ' Coffee '});

Geonear command

Although the find () function is usually first, MongoDB provides a geonear command to perform similar functions. The geonear command returns the distance from the query point to each point in the query results, and some troubleshooting information is also available.

The legitimate options are: "Near", "Num", "MaxDistance", "Distancemultiplier" and "query".

The code is as follows Copy Code

> 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
}


The above command returns the nearest 10 points of distance (50,50). (The Loc field is automatically determined when checking the 2d index above the collection)

If you need to increase the filter, you can do this:

The code is as follows Copy Code

> Db.runcommand ({geonear: "Places", near: [M, M], Num:10,
... query: {type: "Museum"}});


Query can be any regular MONGO query.

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.