Now our query failed because we had no geospatial index. We need one for the near query here,
so how can we add such an index,
it's pretty straightforward.
Just as with other indexes, we use create index to add such index and then, we add the index on the location
field because that is where we store our geo data
in this example, again if you named that field differently,
definitely use your name here,
you have to.
And then the type of the index is now not 1 or -1,
we don't sort it ascending or descending,
it's also not text because it's not a text index,
it's a special 2D sphere index, written like this,
whoops, not like this, like this, 2d sphere in quotation marks.
With this, we created a geospatial index on the location field
and now if we repeat that query from before, it does succeed and we can also pretty print that and we
see that it found this one point.
Now it found this one point but that doesn't really tell us too much,
it's near the location we added
but how is near defined?
Well near doesn't make much sense unless we restrict it,
so typically what you would do is you would not just pass a geometry to near as we're doing it here but
you would also pass another argument and define a max and maybe also a min distance.
Now max distance is simply a value in meters here,
so if I define like 30 meters, I should actually not find anything,
we can also add the min distance and say it should at least be 10 meters away.
So if I add this, I actually don't find anything and that makes sense because if we have a look at Google
Maps, this is the place, the California Academy of Sciences
and this is where we are
and that seems to be a bit further away,
we can actually measure the distance by right clicking onto the map and measuring a distance and then
if I click here, I can measure the distance to the California Academy of Sciences and it seems to be
around 435,36 meters.
Let's validate this by repeating the query and I'll set the max distance to 400,
so this still should not suffice and it does not. Now if I set it to 440, looks like a little
bit off of my place, so let's set it to 500
and now we find the place,
so now we are within 10 and 500 meters and therefore, we find our favorite place.
And this of course is a great query because it allows us to find out which places are near us in a certain
radius which of course is off my question you want to answer in an application.