ElasticSearch学习笔记(五)Bucket聚合、Metric聚合

前言

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) {
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

维先生d

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值