yasithlokuge
yasithlokuge

Reputation: 263

How to get the nearest location(geo point) to a given geo point using Elasticsearch Geo queries

I have a set of locations(geo points) indexed in Elasticsearch. Can someone please suggest a way to get the nearest geo point to a given geo point using the elasticsearch geo queries. I have already tried using Geo Distance query, however it requires me to provide the distance to specify the radius of the circle centred on the specified location. I'm looking for an alternative solution which can return the nearest location regardless of the distance. Suggestions are appreciated.

Upvotes: 1

Views: 2176

Answers (1)

Val
Val

Reputation: 217334

The best way to do it is to leverage distance sorting and retrieve the closest geo location:

GET my-index/_search
{
  "size": 1,                                <--- return top 1
  "sort" : [
    {
      "_geo_distance" : {
          "location-field" : [-70, 40],     <--- center location
          "order" : "asc",                  <--- sorted by closest distance
          "unit" : "km",
          "mode" : "min",
          "distance_type" : "arc",
          "ignore_unmapped": true
      }
    }
  ],
  "query" : {
    "match_all" : {}
  }
}

Upvotes: 2

Related Questions