Tuesday 19 January 2016

Indexing and Searching Geo points using Elasticsearch

Elasticsearch allows users to index geo points as a part of document. The Elasticsearch provides an inbuilt datatype named ‘geo_point’ to get the latitude and longitude data indexed.

Let’s see how the geo points can be stored and searched with a simple example.

Mapping data:

curl -XPUT http://localhost:9200/simplyjava/user -d '{
                " user":{
                        "properties": {
                        "location":{
                             "type":" geo_point"
                        }
          }
    }
}’

Indexing data:

The data for geo_points can be indexed using the below code snippet.

curl -XPOST http://localhost:9200/simplyjava/user/testuser1 -d '{
"location":{
                                     "lat":"80.234",
                                     "lon":"-120.4"   
}
}’

Searching data:

Below code can be used to retrieve the list of people who are within a particular mile radius from a geo location.

curl -XGET 'http://localhost:9200/simplyjava/user/_search?pretty=true' -d '{
  "query": {
"filtered":{
                   "filter" : {
                         "geo_distance" : {
                              "distance" : "1000miles",
                                      "location" : {
                                     "lat" : 70.12,
                                      "lon" : -120.4
                                     }
                         }
            }
       }
  }
}'

Elasticsearch Response:

{
   "took": 131,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "simplyjava",
            "_type": "user",
            "_id": "1",
            "_score": 1,
            "_source": {
               "location": {
                  "lat": "80.234",
                  "lon": "-120.4"
               }
            }
         }
      ]
   }

}

No comments:

Post a Comment