Elasticsearch实战小案例(黑马旅游)

本文介绍了如何使用Elasticsearch和Java的RestHighLevelClient实现搜索分页功能,详细讲解了从创建请求参数类,编写Controller,到服务层的方法实现。接着,文章探讨了添加条件过滤功能,包括城市、品牌、星级和价格范围等。此外,还讨论了如何实现广告置顶的逻辑。最后,作者提醒读者这些技术需要通过实践来巩固。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

例如:本笔记是学习黑马视频所总结的


一、搜索分页功能

1.首先运行项目,浏览器访问

 2.点击搜索,查看http请求,根据请求编写路径地址、请求参数

 

  我们可以看到请求路径和请求方法(POST)

  请求参数有这些 key,page,size,sortBy

3.根据请求参数编写代码

3.1 请求参数封装一个类,返回结果类封装一个类

@Data
public class RequestParams {
    private String key;
    private Integer page;
    private Integer size;
    private String sortBy;

}



@Data
public class PageResult {
    private Long total;
    private List<HotelDoc> hotels;
    public PageResult(Long total, List<HotelDoc> hotels) {
        this.total = total;
        this.hotels = hotels;
    }

}

3.2 编写Controller层

@RestController
@RequestMapping("/hotel")
public class Controller {
    @Resource
    private IHotelService hotelService;
    
    @PostMapping("/list")
    public PageResult list(@RequestBody RequestParams params) {
        return hotelService.search(params);
    }
}

3.3 在编写方法前需要将client注入到Spring容器中 

@MapperScan("cn.itcast.hotel.mapper")
@SpringBootApplication
public class HotelDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(HotelDemoApplication.class, args);
    }
    @Bean
    public RestHighLevelClient getClient(){
        return new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.155.44.123:9200")
//换成自己电脑es的访问地址
        ));
}
}

3.4 编写查询方法 

public interface IHotelService extends IService<Hotel> {
    PageResult search(RequestParams params);
}

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {

        try {
            //准备request对象
            SearchRequest request = new SearchRequest("hotel");
            String key = params.getKey();
            if (StringUtils.isEmpty(key)) {
                request.source().query(QueryBuilders.matchAllQuery());
            } else {
                request.source().query(QueryBuilders.matchQuery("all", key));
            }
            //分页查询
            Integer size = params.getSize();
            Integer page = params.getPage();
            request.source().from((page - 1) * size).size(size);
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            SearchHits searchHits = response.getHits();
            //获取总条数
            Long total = searchHits.getTotalHits().value;
            //文档数组
            SearchHit[] hits = searchHits.getHits();
            //遍历打印结果
            ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                //反序列化
                HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
                hotelDocs.add(hotelDoc);
            }
            return  new PageResult(total, hotelDocs);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

4.测试 

二、条件过滤

1.修改RequestParams类,添加过滤条件需要的参数

@Data
public class RequestParams {
    private String key;
    private Integer page;
    private Integer size;
    private String sortBy;
    private String city;
    private String brand;
    private String starName;
    private String minPrice;
    private String maxPrice;

}

2. 修改search方法

 @Override
    public PageResult search(RequestParams params) {

        try {
            //准备request对象
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            buildBasicQuery(params,request);
            //分页查询
            Integer size = params.getSize();
            Integer page = params.getPage();
            request.source().from((page - 1) * size).size(size);
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            SearchHits searchHits = response.getHits();
            //获取总条数
            Long total = searchHits.getTotalHits().value;
            //文档数组
            SearchHit[] hits = searchHits.getHits();
            //遍历打印结果
            ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                //反序列化
                HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
                hotelDocs.add(hotelDoc);
            }
            return new PageResult(total, hotelDocs);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private static void buildBasicQuery(RequestParams params,SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        //判断搜索框中是否为空
        if (StringUtils.isEmpty(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //条件过滤
        if(StringUtils.isNotEmpty(params.getCity())){
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        if(StringUtils.isNotEmpty(params.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if(StringUtils.isNotEmpty(params.getStarName())){
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        if(StringUtils.isNotEmpty(params.getMaxPrice())&& StringUtils.isNotEmpty(params.getMinPrice())){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }
        request.source().query(boolQuery);
    }

3.测试查看结果

三、查看附近酒店

1.当点击定位时,出现新的参数location。所以在请求参数中添加字段

 

 2.在方法中添加查询条件

3.运行测试 

可以看到距离我最近的酒店十万八千里,哈哈哈

四、广告置顶

1.分析 

2.改写查询代码

 3.后台更新一些打广告的数据,也就是isAD=true

4.测试 

 


总结

     以上就是今天要讲的内容,本文简单介绍了一些常用的操作,这些操作需要大量的练习才能熟练掌握。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值