|
| 1 | +Geospatial Indexing Example |
| 2 | +=========================== |
| 3 | + |
| 4 | +.. testsetup:: |
| 5 | + |
| 6 | + from pymongo import Connection |
| 7 | + connection = Connection() |
| 8 | + connection.drop_database('geo_example') |
| 9 | + |
| 10 | +This example shows how to create and use a :data:`~pymongo.GEO2D` |
| 11 | +index in PyMongo. |
| 12 | + |
| 13 | +.. note:: 2D indexes require server version **>= 1.3.4**. Support for |
| 14 | + 2D indexes also requires PyMongo version **>= 1.5.1**. |
| 15 | + |
| 16 | +.. mongodoc:: geo |
| 17 | + |
| 18 | +Creating a Geospatial Index |
| 19 | +--------------------------- |
| 20 | + |
| 21 | +Creating a geospatial index in pymongo is easy: |
| 22 | + |
| 23 | +.. doctest:: |
| 24 | + |
| 25 | + >>> from pymongo import Connection, GEO2D |
| 26 | + >>> db = Connection().geo_example |
| 27 | + >>> db.places.create_index([("loc", GEO2D)]) |
| 28 | + u'loc_2d' |
| 29 | + |
| 30 | +Inserting Places |
| 31 | +---------------- |
| 32 | + |
| 33 | +Locations in MongoDB are represented using either embedded documents |
| 34 | +or lists where the first two elements are coordinates. Here, we'll |
| 35 | +insert a couple of example locations: |
| 36 | + |
| 37 | +.. doctest:: |
| 38 | + |
| 39 | + >>> db.places.insert({"loc": [2, 5]}) |
| 40 | + ObjectId('...') |
| 41 | + >>> db.places.insert({"loc": [30, 5]}) |
| 42 | + ObjectId('...') |
| 43 | + >>> db.places.insert({"loc": [1, 2]}) |
| 44 | + ObjectId('...') |
| 45 | + >>> db.places.insert({"loc": [4, 4]}) |
| 46 | + ObjectId('...') |
| 47 | + |
| 48 | +Querying |
| 49 | +-------- |
| 50 | + |
| 51 | +Using the geospatial index we can find documents near another point: |
| 52 | + |
| 53 | +.. doctest:: |
| 54 | + |
| 55 | + >>> for doc in db.places.find({"loc": {"$near": [3, 6]}}).limit(3): |
| 56 | + ... repr(doc) |
| 57 | + ... |
| 58 | + "{u'loc': [2, 5], u'_id': ObjectId('...')}" |
| 59 | + "{u'loc': [4, 4], u'_id': ObjectId('...')}" |
| 60 | + "{u'loc': [1, 2], u'_id': ObjectId('...')}" |
| 61 | + |
| 62 | +It's also possible to query for all items within a given rectangle |
| 63 | +(specified by lower-left and upper-right coordinates): |
| 64 | + |
| 65 | +.. doctest:: |
| 66 | + |
| 67 | + >>> for doc in db.places.find({"loc": {"$within": {"$box": [[2, 2], [5, 6]]}}}): |
| 68 | + ... repr(doc) |
| 69 | + ... |
| 70 | + "{u'loc': [4, 4], u'_id': ObjectId('...')}" |
| 71 | + "{u'loc': [2, 5], u'_id': ObjectId('...')}" |
| 72 | + |
| 73 | +Or circle (specified by center point and radius): |
| 74 | + |
| 75 | +.. doctest:: |
| 76 | + |
| 77 | + >>> for doc in db.places.find({"loc": {"$within": {"$center": [[0, 0], 6]}}}): |
| 78 | + ... repr(doc) |
| 79 | + ... |
| 80 | + "{u'loc': [1, 2], u'_id': ObjectId('...')}" |
| 81 | + "{u'loc': [2, 5], u'_id': ObjectId('...')}" |
| 82 | + "{u'loc': [4, 4], u'_id': ObjectId('...')}" |
0 commit comments