文章目录
前言
ElasticSearch学习笔记(一)倒排索引、ES和Kibana安装、索引操作
ElasticSearch学习笔记(二)文档操作、RestHighLevelClient的使用
ElasticSearch学习笔记(三)RestClient操作文档、DSL查询文档、搜索结果排序
ElasticSearch学习笔记(四)分页、高亮、RestClient查询文档
9 项目实战
9.3 我周边的酒店
- 1)需求分析
点击页面右侧的地图组件的定位按钮,将位置信息发送给后台,后台基于位置坐标,按照距离远近对附近的酒店进行排序。
- 2)修改
RequestParams
参数,接收location
字段
// cn.hsgx.hotel.pojo.RequestParams
@Data
public class RequestParams {
private String key;
private Integer page;
private Integer size;
private String sortBy;
private String brand;
private String city;
private String starName;
private Integer minPrice;
private Integer maxPrice;
// 位置信息
private String location;
}
- 3)在
HotelServiceImpl
实现类的handleQueryParams()
方法中,添加根据地理位置排序功能
// cn.hsgx.hotel.service.impl.HotelServiceImpl
private void handleQueryParams(RequestParams params, SearchRequest request) {
// ......
// 1.6 根据地理位置排序
String location = params.getLocation();
if(StringUtils.isNotBlank(location)) {
request.source().sort(SortBuilders
.geoDistanceSort("location", new GeoPoint(location))
.order(SortOrder.ASC)
.unit(DistanceUnit.KILOMETERS)
);
}
// 2.设置查询条件
request.source().query(functionScoreQuery);
}
- 4)功能测试
查阅日志中打印的DSL语句及其返回信息:
- 5)获取附近每个酒店距离当前位置的具体距离值
根据距离进行排序时,具体的距离值也会一起返回,只是不在source
部分:
因此在结果解析时,除了解析source
部分,还要得到sort
部分,也就是排序的距离,然后放到响应结果中。
修改HotelServiceImpl
类中的handleResponse
方法,添加对sort
值的获取:
// cn.hsgx.hotel.service.impl.HotelServiceImpl
private PageResult handleResponse(SearchResponse response) {
SearchHits searchHits = response.getHits();
// 4.1.总条数
long total = searchHits.getTotalHits().value;
// 4.2.获取文档数组
SearchHit[] hits = searchHits.getHits();
// 4.3.遍历
List<HotelDoc> hotels = new ArrayList<>(hits.length);
for (SearchHit hit : hits) {