Before you can use the geospatial queries, you must have a geospatial index.

Before you can use the geospatial queries, you must have a geospatial index.


Btree indexes have been covered quite thoroughly in the preceeding section, however we have not yet described GeoSpatial indexes.First of all, let us discuss why geospatial indexing might be useful at all.Hence the need for some sort of GeoSpatial indexing, to speed up these searches.Using $near, you can efficiently sort documents in a collection by their proximity to a given point.The $within operator allows you to specify a bounds for the query.Supported boundary definitions include $box for a rectangular shape, $circle for a circle.Before you can use the geospatial queries, you must have a geospatial index.This can have some important implications for schema design which is why it is good to know from the outset.Once the documents in your collection have their location properties correctly formed, we can create the geospatial index.For exmaple, if you know that you will be searching your collection by both username and user_location properties, you could create a compound geo index across both fields.This can help to work around the single geospatial index limitation in many cases.# Create geospatial index on ’user_location’ property.# Create geospatial index on ’user_location’ property.The $near operator is pretty easy to understand, so we shall start there.As has already been explained, $near will sort query results by proximity to specified point.By default, $near will try to find the closest 100 results.This takes a lot of time.In most cases, a max distance of around 5 degrees should be sufficient.1 degree is roughly 69 miles.In the real world, these boundaries are fuzzy and changing constantly, however there are good enough databases available for them to be useful.As with $maxDistance mentioned previously, the units of the radius are degrees.All the queries we’ve mentioned so far which make use of a geospatial index actually are not entirely accurate.This is because they use a flat earth model where each arc degree of latitude and longitude translates to the same distance everywhere on the earth.In reality, the earth is a sphere and so these values differ depending upon where you are.The new spherical model can be used by employing the $nearSphere and $circleSphere variants on the $near and $circle operators.Secondly, unlike the $near and $center operators we just described, the units for distances with $nearSphere and $centerSphere are always expressed in radians.This includes when using $maxDistance with $nearSphere or $centerSphere.Do not blindly assume that results will always have the properties you expect.Check for their presence before accessing them.Although Python will generally raise a KeyError and stop execution, depending on your application this still may result in loss of data integrity.



kate5

11 Blog posts

Comments