-
Notifications
You must be signed in to change notification settings - Fork 9
Tutorial: Sorting by Geospatial Distance
If you have geocoded documents, it's natural to want to execute a search and have the results ordered by distance from a point. This can be accomplished via multiple geo constraints in structured queries.
For this tutorial, let's say that there is geospatial indexed called location that was previously setup using the geo management endpoint.
To order the search results so that higher results are located further from a point, we're going to use a number of concentric circles, each with a decreasing weight. Here's what the structured query would look like:
{"or": [
{
"geo": "location",
"weight": 10,
"region": { "circle": {
"radius": 1,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 9,
"region": { "circle": {
"radius": 5,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 8,
"region": { "circle": {
"radius": 10,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 7,
"region": { "circle": {
"radius": 20,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 6,
"region": { "circle": {
"radius": 50,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 5,
"region": { "circle": {
"radius": 100,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 4,
"region": { "circle": {
"radius": 250,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 3,
"region": { "circle": {
"radius": 500,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 2,
"region": { "circle": {
"radius": 1000,
"latitude": 0,
"longitude": 0
}}
},
{
"geo": "location",
"weight": 1,
"region": { "circle": {
"radius": 2000,
"latitude": 0,
"longitude": 0
}}
}
]}
Notice how the weight of each geo constraint is decreasing as the radius of the circle is increasing. The weight is what dictates the order that the results come back in, so those that are closer will be returned higher in the results.
This is quite a course grain way of ordering from a location. But adding more geo constraints into the or query will allow for more precision.