A.2. Adding distance to your sort criteria

Using the get-together example from the main chapters of the book, let’s say your coordinates are 40,–105 and you need to find the event about Elasticsearch closest to you. To do that, you need to add a sort criteria called _geo_distance, where you specify your current location, as shown in the following listing.

Listing A.1. Sorting events by distance

You can also specify an array of multiple reference points and use mode to decide whether the sort value will be the mim/max/avg distance between the reference points and the point stored in the document:

"_geo_distance" : {

"location.geolocation" : ["40,-105", "42,-107"],

"order" : "asc",

"unit" : "km",

"mode" : "avg"

This is useful, for example, when you have multiple points of interest and you want to find a hotel that’s close to all of them.

A.2.1. Sorting by distance and other criteria at the same time

A search like the previous one is useful when distance is your only criteria. If you want to include other criteria in the equation, such as the document’s score, you can use the function_score query that we introduced in chapter 6. This way, you can generate a final score based on the initial score from your query plus the distance from your point of interest.

The following listing shows such a query: an event will score linearly lower the farther it is from you. At 100 km, the original score would be cut by half (decay=0.5).

Listing A.2. Taking distance into account when calculating the score

You might be tempted to think that such scripts bring the best of both worlds: relevance from your query and the geospatial dimension. Although the function_score query is very powerful indeed, running it as shown in listing A.2 is expensive in terms of speed, especially when you have lots of documents, because it has to calculate the distance from origin of all matching documents. A faster way could be to search your events as usual and filter only those that are within a certain distance.