I have implemented Elastic Search - Java API to search data based on the distance.
QueryBuilder geoQuery = QueryBuilders.geoDistanceQuery("article_location.location").point(lat , lon).distance(5 , DistanceUnit.KILOMETERS);
QueryBuilders.boolQuery().filter(geoQuery);
However, I would like to get distance in each result from input lat/lon. Is there any way to specify that?
I see in elastic DSL we can do it via script_fields
but do not know how to get it via Java API.
"script_fields": {
"distance": {
"script": "doc['latlong'].distanceInKm(lat, lon)"
}
Im using
elasticsearch-rest-high-level-client 7.9.2 version.
CodePudding user response:
The Java client also allows you to add script fields to your query, simply like this:
sourceBuilder.query(...);
// add lat/lon as parameters
Map<String, Object> params = new HashMap<String, Object>();
params.put("lat", lat);
params.put("lon", lon);
// create the script
Script script = new Script(ScriptType.INLINE, "painless", "doc['latlong'].distanceInKm(params.lat, params.lon)", params);
// add the script field to the source query builder
sourceBuilder.scriptField("distance", script);