Search code examples
elasticsearchelastica

Sorting results based on location using elastica


I am trying to learn ElasticSearch using elastica to connect in and finding information hard to get in order to understand how to query it.

So basically what I am trying to do is, I have inserted data into elastic search, added geo coordinates in and now what i need to do is to be able to run a query that will sort the results i get by closest to farthest.

I wanted to find all the stores in my state, then order them by which one is closest to my current location.

so given a field called "state" and field called "point" which is an array holding long/Lat using elastica what would the query be?

Thanks for any help that you can give me.


Solution

  • First, you need to map your location field as type geo_point (this needs to be done before inserting any data)

    {
        "stores" : {
            "properties" : {
                "point" : {
                    "type" : "geo_point"
                }
            }
        }
    }
    

    After that, you can simply sort your search by _geo_distance

    {
        "sort" : [
            {
                "_geo_distance" : {
                    "stores.point" : [-70, 40], // <- reference starting position
                    "order" : "asc",
                    "unit" : "km"
                }
            }
        ],
        "query" : {
            "match_all" : {}
        }
    }
    

    For Elastica, have a look at their docs regarding mapping and query building, and read the unit tests.