启动ES服务
docker start es-node01 es-node02 es-node03
使用es-head连接es集群
插件安装谷歌浏览器即可
搜索附近的代码
@Override
public PageInfo<UserLocationVo> queryUserFromLocation(Double longitude, Double latitude, Double distance, Integer page, Integer pageSize) {
PageInfo<UserLocationVo> pageInfo = new PageInfo<>();
pageInfo.setPageNum(page);
pageInfo.setPageSize(pageSize);
String fieldName = "location";
//2. 实现了SearchQuery接口,构造分页、排序
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
//3. 分页
searchQueryBuilder.withPageable(pageRequest);
//5. 构建布尔查询
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
//7. 以一个点为中心,指定范围查询
GeoDistanceQueryBuilder geoDistanceQueryBuilder = new GeoDistanceQueryBuilder(fieldName);
//8. 中心点
geoDistanceQueryBuilder.point(new GeoPoint(latitude, longitude));
//9。 距离(画圆的半径)单位:公里
geoDistanceQueryBuilder.distance(distance / 1000, DistanceUnit.KILOMETERS);
//6. must连接geo查询
boolQueryBuilder.must(geoDistanceQueryBuilder);
//4. 传入查询条件
searchQueryBuilder.withQuery(boolQueryBuilder);
//10. 排序,由近到远排序
GeoDistanceSortBuilder geoDistanceSortBuilder = new GeoDistanceSortBuilder(fieldName, latitude, longitude);
geoDistanceSortBuilder.order(SortOrder.ASC); //正序排序
geoDistanceSortBuilder.unit(DistanceUnit.KILOMETERS); //设置单位
searchQueryBuilder.withSort(geoDistanceSortBuilder);
//1. 执行查询
AggregatedPage<UserLocation> aggregatedPage = this.elasticsearchTemplate.queryForPage(searchQueryBuilder.build(), UserLocation.class);
if(CollUtil.isEmpty(aggregatedPage.getContent())){
return pageInfo;
}
//11. 封装结果集
pageInfo.setRecords(UserLocationVo.formatToList(aggregatedPage.getContent()));
return pageInfo;
}