/**
* 根据经纬度定位用户所在地
*
* @param token
* @return
*/
@PostMapping("...")
public AppResDto searchAreaByLatAndLon(@RequestParam("token") String token,
@RequestParam("lat") Double lat,
@RequestParam("lon") Double lon) throws Exception {
//设定搜索半径
GeoDistanceQueryBuilder queryBuilder = QueryBuilders.geoDistanceQuery("location")
.point(lat, lon)
.distance(1500, DistanceUnit.KILOMETERS)
.geoDistance(GeoDistance.PLANE);
//按距离排序
GeoDistanceSortBuilder sort = SortBuilders.geoDistanceSort("location", lat, lon);
sort.order(SortOrder.ASC);
sort.point(lat, lon);
//构建检索
SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource()
.from(0)
.size(20)
.query(queryBuilder )
.sort(sort);
SearchHits searchHits = elasearchService.searchDocument(ElsIndexEnums.rz_area.getIndex(), searchSourceBuilder);
ArrayList<Map> arrayList = new ArrayList<>();
{//控制台测试显示!生产删除!
searchHits.forEach(hit->{
Map map = new HashMap();
map.put("complete_path", hit.getSourceAsMap().get("complete_path"));
//获取距离值,并保留两位小数点
BigDecimal geoDis = new BigDecimal((Double) hit.getSortValues()[0]);
//坐标
Object location2 = hit.getSourceAsMap().get("location");
Map<String, Object> hitMap = hit.getSourceAsMap();
//计算距离
hitMap.put("geoDistance", geoDis.setScale(0, BigDecimal.ROUND_HALF_DOWN));
map.put("range", hit.getSourceAsMap().get("geoDistance"));
arrayList.add(map);
System.out.println(hit.getSourceAsMap().get("complete_path") + "的坐标:" +
location2 + "与我的距离" +
hit.getSourceAsMap().get("geoDistance") +
DistanceUnit.METERS.toString());
});
}
Map<String, Object> map = new HashMap<>();
if (searchHits.getHits().length > 0) {
map = searchHits.getHits()[0].getSourceAsMap();
}
//return AppResDto.success(arrayList);
return AppResDto.success(map);
}
今天的文章Java之elasticsearch geo 距离排序检索分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/13031.html