SpringBoot 实现 elasticsearch 查询操作(RestHighLevelClient 的案例实战)

news/2024/11/8 0:10:21/

文章目录

  • 1. 环境准备
  • 1. 查询全部
  • 2. 根据 name 查询 match 分词查询
  • 3. 根据 name 和 品牌查询 multiMatch 分词查询
  • 4. 根据 brand 查询 match 分词查询
  • 5. 按照价格 范围查询
  • 6. 精确查询
  • 7. boolQuery
  • 8. 分页
  • 9. 高亮查询
  • 9. 公共解析


在这里插入图片描述

上一节讲述了 SpringBoot 实现 elasticsearch 索引操作,这一章节讲述 SpringBoot 实现 elasticsearch 查询操作。


1. 环境准备

案例用到的索引库结构

PUT /hotel
{"mappings": {"properties": {"id": {"type": "keyword"},"name":{"type": "text","analyzer": "ik_max_word","copy_to": "all"},"address":{"type": "keyword","index": false},"price":{"type": "integer"},"score":{"type": "integer"},"brand":{"type": "keyword","copy_to": "all"},"city":{"type": "keyword","copy_to": "all"},"starName":{"type": "keyword"},"business":{"type": "keyword"},"location":{"type": "geo_point"},"pic":{"type": "keyword","index": false},"all":{"type": "text","analyzer": "ik_max_word"}}}
}

1. 查询全部

@GetMapping("/searchAll")
public List<HotelDoc> searchAll() throws Exception {//1.创建请求语义对象SearchRequest searchRequest = new SearchRequest("索引名称");// QueryBuilders: 构建查询类型searchRequest.source().query(QueryBuilders.matchAllQuery());SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);return handleResponse(searchResponse);
}

2. 根据 name 查询 match 分词查询

 @GetMapping("/searchByName/{name}")
public List<HotelDoc> searchByName(@PathVariable("name") String name) throws Exception {//1.创建请求语义对象SearchRequest searchRequest = new SearchRequest("索引名称");// QueryBuilders: 构建查询类型searchRequest.source().query(QueryBuilders.matchQuery("name", name));SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);return handleResponse(searchResponse);
}

3. 根据 name 和 品牌查询 multiMatch 分词查询

@GetMapping("/searchByNameAndBrand/{name}")
public List<HotelDoc> searchByNameAndBrand(@PathVariable("name") String name) throws Exception {//1.创建请求语义对象SearchRequest searchRequest = new SearchRequest("索引名称");// QueryBuilders: 构建查询类型searchRequest.source().query(QueryBuilders.multiMatchQuery(name,"name","brand"));SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);return handleResponse(searchResponse);
}

4. 根据 brand 查询 match 分词查询

@GetMapping("/searchByBrand/{name}")
public List<HotelDoc> searchByBrand(@PathVariable("name") String name) throws Exception {//1.创建请求语义对象SearchRequest searchRequest = new SearchRequest("索引名称");// QueryBuilders: 构建查询类型searchRequest.source().query(QueryBuilders.matchQuery("brand", name));SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);return handleResponse(searchResponse);
}

5. 按照价格 范围查询

 @GetMapping("/searchByPrice/{low}/{high}")
public List<HotelDoc> searchByPrice(@PathVariable("low") String low, @PathVariable("high") String high) throws Exception {//1.创建请求语义对象SearchRequest searchRequest = new SearchRequest("索引名称");// QueryBuilders: 构建查询类型searchRequest.source().query(QueryBuilders.rangeQuery("price").gte(low).lte(high));SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);return handleResponse(searchResponse);
}

6. 精确查询

@GetMapping("/termQueryCity/{city}")
public List<HotelDoc> termQueryCity(@PathVariable("city") String city) throws Exception {//1.创建请求语义对象SearchRequest searchRequest = new SearchRequest("索引名称");// QueryBuilders: 构建查询类型SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//searchSourceBuilder.query(QueryBuilders.termQuery("city", city)); 这行有点小问题//	https://zhuanlan.zhihu.com/p/270426807 参考searchSourceBuilder.query(QueryBuilders.termQuery("city.keyword", city));searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);return handleResponse(searchResponse);
}

7. boolQuery

@GetMapping("/testBool")
public List<HotelDoc> testBool() throws Exception {// 1.准备RequestSearchRequest request = new SearchRequest("索引名称");// 2.准备DSL// 2.1.准备BooleanQueryBoolQueryBuilder boolQuery = QueryBuilders.boolQuery();// 2.2.添加termboolQuery.must(QueryBuilders.termQuery("city.keyword", "杭州"));// 2.3.添加rangeboolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));request.source().query(boolQuery);// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应return handleResponse(response);
}

8. 分页

 @GetMapping("/testPageAndSort/{currentPage}/{pageSize}")
public List<HotelDoc> testPageAndSort(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize) throws Exception {// 页码,每页大小// 1.准备RequestSearchRequest request = new SearchRequest("索引名称");// 2.准备DSL// 2.1.queryrequest.source().query(QueryBuilders.matchAllQuery());// 2.2.排序 sortrequest.source().sort("price", SortOrder.ASC);// 2.3.分页 from、sizerequest.source().from((currentPage - 1) * pageSize).size(pageSize);// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应return handleResponse(response);
}

9. 高亮查询

 @GetMapping("/testHighlight/{name}")
void testHighlight(@PathVariable("name") String name) throws Exception {// 1.准备RequestSearchRequest request = new SearchRequest("索引名称");// 2.准备DSL// 2.1.queryrequest.source().query(QueryBuilders.matchQuery("name", name));// 2.2.高亮request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));// 3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析响应handleResponse2(response);
}

9. 公共解析

private List<HotelDoc> handleResponse(SearchResponse response) throws Exception {// 获取命中的所有内容SearchHits searchHits = response.getHits();// 获取命中的总条数long count = searchHits.getTotalHits().value;System.out.println("命中的条数为: "+ count);// 获取命中的文档对象数组SearchHit[] hits = searchHits.getHits();List<HotelDoc> docList = new ArrayList<>();for (SearchHit hit : hits) {// 解析每一个hit对象得到对应的文档数据String json = hit.getSourceAsString();//  HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);docList.add(JSON.parseObject(json, HotelDoc.class));}//destroy();return docList;
}private void handleResponse2(SearchResponse response) {// 4.解析响应SearchHits searchHits = response.getHits();// 4.1.获取总条数long total = searchHits.getTotalHits().value;System.out.println("共搜索到" + total + "条数据");// 4.2.文档数组SearchHit[] hits = searchHits.getHits();// 4.3.遍历for (SearchHit hit : hits) {// 获取文档sourceString json = hit.getSourceAsString();// 反序列化HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);// 获取高亮结果Map<String, HighlightField> highlightFields = hit.getHighlightFields();if ( !CollectionUtils.isEmpty(highlightFields) ) {// 根据字段名获取高亮结果HighlightField highlightField = highlightFields.get("name");if (highlightField != null) {// 获取高亮值String name = highlightField.getFragments()[0].string();// 覆盖非高亮结果hotelDoc.setName(name);}}System.out.println("hotelDoc = " + hotelDoc);}
}


在这里插入图片描述


http://www.ppmy.cn/news/665168.html

相关文章

iOS 2015年3月苹果新的审核标准(中文)

请阅读以下许可协议的条款和条件之前仔细下载或使用Apple软件。这些条款和条件构成了您与苹果的法律协议。 iOS开发者计划许可协议 目的 你想用苹果软件&#xff08;定义见下文&#xff09;制定的一个或多个应用程序&#xff08;定义见​​下文&#xff09;&#xff0c;运行…

IOS蓝牙开发

蓝牙常遇缩写 MFI make for ipad ,iphone, itouch 专们为苹果设备制作的设备 BLE buletouch low energy&#xff0c;蓝牙4.0设备因为低耗电&#xff0c;所以也叫做BLE peripheral,central 外设和中心,发起连接的时central&#xff0c;被连接的设备为perilheral serv…

2015年3月苹果新的审核标准(中文)

请阅读以下许可协议的条款和条件之前仔细下载或使用Apple软件。这些条款和条件构成了您与苹果的法律协议。 的iOS开发者计划许可协议 目的 你想用苹果软件&#xff08;定义见下文&#xff09;制定的一个或多个应用程序&#xff08;定义见​​下文&#xff09;&#xff0c;运行…

【Mac/ios】苹果产品的蓝牙配件的设计指导

1. 简介 这个设计指导文档面向的是使用蓝牙技术与苹果产品通信的硬件配件&#xff0c;包括Mac&#xff0c;iPhone&#xff0c;iPad和iPod。 为了与当前和未来的苹果产品兼容&#xff0c;蓝牙配件应遵循这个文档中的规范。一个苹果产品需要蓝牙配件上的特性可用性遵循这个文档…

苹果产品的蓝牙配件的设计指导

1. 简介 这个设计指导文档面向的是使用蓝牙技术与苹果产品通信的硬件配件&#xff0c;包括Mac&#xff0c;iPhone&#xff0c;iPad和iPod。 为了与当前和未来的苹果产品兼容&#xff0c;蓝牙配件应遵循这个文档中的规范。一个苹果产品需要蓝牙配件上的特性可用性遵循这个文档…

苹果电池测试软件i-t,Apple Watch出行绝佳伴侣,CHOETECH磁力充电座评测T313

在户外没有电源插座的情况下我们都习惯于使用移动电源为自己的手机充电&#xff0c;随着科技的不断发展&#xff0c;智能穿戴的产品也出现在了我们的视野当中&#xff0c;以Apple Watch为代表的智能手表也加入到了我们的生活并逐渐融入到了生活的方方面面。但是手表的充电必须要…

苹果MFI bluetooth认证开发过程:iDevice和accessory

研究材料&#xff1a; Accessory Interface Specification for Apple Devices.pdf iPodAuthenticationCoprocessorSpec2.0CR1 如果需要更详细的协议说明&#xff0c;可以下载MFI Accessory Firmware Specification PDF &#xff08;文档来自苹果授权方&#xff0c;如有侵权…

MYSQL-UNION

语法: UNION 操作符用来合并两个 SELECT 语句的结果 SELECT statement UNION [DISTINCT | ALL] SELECT statement UNION 中的 SELECT 语句中的列数、列顺序必须相同 UNION是双目操作符,需要两个SELECT语句作为操作数,UNION后面可以接DISTINCT或者ALL 如果不写DISTINCT或者…