Reputation: 13
I am using elastic4s version 1.6.2 and need to write a query which searches for a given geo location, sorts results by distance and also returns the distance. I can do this using get request in curl but struggling to find the correct syntax and example got geolocation sort.
case class Store(id: Int, name: String, number: Int, building: Option[String] = None, street: String, postCode: String,county: String, geoLocation: GeoLocation)
case class GeoLocation(lat: Double, lon: Double)
val createMappings = client.execute {
create index "stores" mappings (
"store" as(
"store" typed StringType,
"geoLocation" typed GeoPointType
)
)
}
def searchByGeoLocation(geoLocation: GeoLocation) = {
client.execute {
search in "stores" -> "store" postFilter {
geoDistance("geoLocation") point(geoLocation.lat, geoLocation.lon) distance(2, KILOMETERS)
}
}
}
Does someone knows how to add the sort by distance from a geo location and get the distance Following curl command works as expected
curl -XGET 'http://localhost:9200/stores/store/_search?pretty=true' -d '
{
"sort" : [
{
"_geo_distance" : {
"geoLocation" : {
"lat" : 52.0333793839746,
"lon" : -0.768937531935448
},
"order" : "asc",
"unit" : "km"
}
}
],
"query": {
"filtered" : {
"query" : {
"match_all" : {}
},
"filter" : {
"geo_distance" : {
"distance" : "20km",
"geoLocation" : {
"lat" : 52.0333793839746,
"lon" : -0.768937531935448
}
}
}
}
} }'
Upvotes: 0
Views: 870
Reputation: 10278
Not an expert in elasti4s
but this query should be equivalent to your curl command:
val geoLocation = GeoLocation(52.0333793839746, -0.768937531935448)
search in "stores" -> "store" query {
filteredQuery filter {
geoDistance("geoLocation") point(geoLocation.lat, geoLocation.lon) distance(20, KILOMETERS)
}
} sort {
geoSort("geoLocation") point (geoLocation.lat, geoLocation.lon) order SortOrder.ASC
}
it prints the following query:
{
"query" : {
"filtered" : {
"query" : {
"match_all" : { }
},
"filter" : {
"geo_distance" : {
"geoLocation" : [ -0.768937531935448, 52.0333793839746 ],
"distance" : "20.0km"
}
}
}
},
"sort" : [ {
"_geo_distance" : {
"geoLocation" : [ {
"lat" : 52.0333793839746,
"lon" : -0.768937531935448
} ]
}
} ]
}
asc
is the default value of sorting so you can remove order SortOrder.ASC
. Just wanted to be explicit in this example.
Upvotes: 2