微服务——RestClient查询文档

快速入门

返回结果直接把json风格的结果封装为SearchReponse对象返回

public class HotelSearchTest {private RestHighLevelClient client;@Testvoid testMatchAll() throws IOException {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSlrequest.source().query(QueryBuilders.matchAllQuery());//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);System.out.println(response);}//执行前初始化@BeforeEachvoid setUp(){this.client=new RestHighLevelClient(RestClient.builder(HttpHost.create("http://xxx.xxx.xxx.xxx:9200")//HttpHost.create("http://xxx.xxx.xxx.xxx:9200") 集群时添加更多的地址));}//销毁@AfterEachvoid tearDown() throws IOException {this.client.close();}
}

 

 响应结果解析 

    @Testvoid testMatchAll() throws IOException {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSlrequest.source().query(QueryBuilders.matchAllQuery());//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);//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);System.out.println("hotelDoc="+hotelDoc);}}

 默认只返回前10条数据 

 

 

 在.source()中query,排序,分页,高亮等功能

QueryBuildes中准备了所有查询,match,match_all,boolean等

match、term、range、bool查询

全文检索查询

 

    @Testvoid testMatch() throws IOException {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSlrequest.source().query(QueryBuilders.matchQuery("all","如家"));//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);//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);System.out.println("hotelDoc="+hotelDoc);}}

对比match和match_all,不同的地方只有一点点,这里直接抽取4往后的公共部分,使用ctrl+alt+m抽取

 

public class HotelSearchTest {private RestHighLevelClient client;@Testvoid testMatchAll() throws IOException {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSlrequest.source().query(QueryBuilders.matchAllQuery());//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleResponse(response);}@Testvoid testMatch() throws IOException {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSlrequest.source().query(QueryBuilders.matchQuery("all","如家"));//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleResponse(response);}private static void handleResponse(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);System.out.println("hotelDoc="+hotelDoc);}}//执行前初始化@BeforeEachvoid setUp(){this.client=new RestHighLevelClient(RestClient.builder(HttpHost.create("http://xxx.xxx.xxx.xxx:9200")//HttpHost.create("http://xxx.xxx.xxx.xxx:9200") 集群时添加更多的地址));}//销毁@AfterEachvoid tearDown() throws IOException {this.client.close();}
}

 精确查询

 

一个boolean查询里面包含了term查询和 range查询

@Testvoid testBool() throws IOException {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSl//2.1准备BooleanQueryBoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//2.2添加termboolQuery.must(QueryBuilders.termQuery("city","上海"));//2.3添加rangeboolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));request.source().query(boolQuery);//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleResponse(response);}

 

 排序和分页

    @Testvoid testPageAndSort() throws IOException {//前端传来页码,每页大小int page=1,size=5;//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSl//2.1准备queryrequest.source().query(QueryBuilders.matchAllQuery());//2.2排序 sortrequest.source().sort("price", SortOrder.ASC);//2.3分页 from,sizerequest.source().from((page-1)*size).size(5);//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleResponse(response);}

 

高亮

构建

    @Testvoid testHighlight() throws IOException {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSl//2.1准备queryrequest.source().query(QueryBuilders.matchQuery("all","如家"));//2.2高亮request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.解析响应handleResponse(response);}

 

 

 解析

 逐层解析json结果

    @Testvoid testHighlight() throws IOException {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSl//2.1准备queryrequest.source().query(QueryBuilders.matchQuery("all","如家"));//2.2高亮request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));//3.发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.解析响应handleResponse(response);}private static void handleResponse(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)) //判断map是否为空的工具类{//根据名字获取高亮结果HighlightField highlightField = highlightFields.get("name");if(highlightField!=null){//获取高亮值String name = highlightField.getFragments()[0].string();//覆盖非高亮结果hotelDoc.setName(name);}}System.out.println("hotelDoc="+hotelDoc);}}

 

 黑马旅游案例——酒店搜索和分页

 定义实体类

用于接收前端传来的参数

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

Controller层中

 返回值定义

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

在启动类中定义一个Bean

@MapperScan("cn.itcast.hotel.mapper")
@SpringBootApplication
public class HotelDemoApplication {public static void main(String[] args) {SpringApplication.run(HotelDemoApplication.class, args);}@Beanpublic RestHighLevelClient client(){return new RestHighLevelClient(RestClient.builder(HttpHost.create("http://xxx.xxx.xxx.xxx:9200")//HttpHost.create("http://xxx.xxx.xxx.xxx:9200") 集群时添加更多的地址));}
}
@RestController
@RequestMapping("hotel")
public class HotelController {@Autowiredprivate IHotelService hotelService;/*** 搜索和分页* @param requestParams* @return*/@PostMapping("/list")public PageResult search(@RequestBody RequestParams requestParams){return hotelService.search(requestParams);}
}

 

Service层中

public interface IHotelService extends IService<Hotel> {PageResult search(RequestParams requestParams);
}
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {@Autowiredprivate RestHighLevelClient client;@Overridepublic PageResult search(RequestParams requestParams) {try {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSl//2.1queryString key= requestParams.getKey();if(key==null||"".equals(key)){  //没有查询内容时直接查询全部request.source().query(QueryBuilders.matchAllQuery());}else {request.source().query(QueryBuilders.matchQuery("all", key));}//2.2分页int page=requestParams.getPage();int size=requestParams.getSize();request.source().from((page-1)*size).size(size);//3.发送请求SearchResponse response= client.search(request, RequestOptions.DEFAULT);//4.解析响应handleResponse(response);return null;} catch (IOException e) {throw new RuntimeException(e);}}private PageResult handleResponse(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遍历List<HotelDoc> hotels=new ArrayList<>();for (SearchHit hit : hits) {//获取文档sourceString json = hit.getSourceAsString();//反序列化HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);hotels.add(hotelDoc);}return new PageResult(total,hotels);}
}

 

成功搜索

 

 黑马旅游案例——条件过滤

修改DTO

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

 

Service层中

修改如下,加了多条件过滤,并抽取出去

    @Overridepublic PageResult search(RequestParams requestParams) {try {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSl//2.1querybuildBasicQuery(requestParams, request);//2.2分页int page=requestParams.getPage();int size=requestParams.getSize();request.source().from((page-1)*size).size(size);//3.发送请求SearchResponse response= client.search(request, RequestOptions.DEFAULT);//4.解析响应return handleResponse(response);} catch (IOException e) {throw new RuntimeException(e);}}private static void buildBasicQuery(RequestParams requestParams, SearchRequest request) {//构建BooleanQueryBoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//关键字搜索String key= requestParams.getKey();if(key==null||"".equals(key)){  //没有查询内容时直接查询全部boolQuery.must(QueryBuilders.matchAllQuery());}else {boolQuery.must(QueryBuilders.matchQuery("all", key));}//城市条件if(requestParams.getCity()!=null&&!requestParams.getCity().equals("")){boolQuery.filter(QueryBuilders.termQuery("city", requestParams.getCity()));}//品牌条件if(requestParams.getBrand()!=null&&!requestParams.getBrand().equals("")){boolQuery.filter(QueryBuilders.termQuery("brand", requestParams.getBrand()));}//星级条件if(requestParams.getStarName()!=null&&!requestParams.getStarName().equals("")){boolQuery.filter(QueryBuilders.termQuery("starName", requestParams.getStarName()));}//价格条件if(requestParams.getMinPrice()!=null&& requestParams.getMaxPrice()!=null){boolQuery.filter(QueryBuilders.rangeQuery("price").gte(requestParams.getMinPrice()).lte(requestParams.getMaxPrice()));}request.source().query(boolQuery);}

 

 黑马旅游案例——我附近的酒店

距离排序 

DTO修改

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

Service中 

 修改如下

新增2.3部分

    @Overridepublic PageResult search(RequestParams requestParams) {try {//1.准备requestSearchRequest request = new SearchRequest("hotel");//2.准备DSl//2.1querybuildBasicQuery(requestParams, request);//2.2分页int page=requestParams.getPage();int size=requestParams.getSize();request.source().from((page-1)*size).size(size);//2.3排序String location = requestParams.getLocation();if(location!=null&&!location.equals("")){request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location)).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));}//3.发送请求SearchResponse response= client.search(request, RequestOptions.DEFAULT);//4.解析响应return handleResponse(response);} catch (IOException e) {throw new RuntimeException(e);}}

DTO修改

@Data
@NoArgsConstructor
public class HotelDoc {private Long id;private String name;private String address;private Integer price;private Integer score;private String brand;private String city;private String starName;private String business;private String location;private String pic;private Object distance;public HotelDoc(Hotel hotel) {this.id = hotel.getId();this.name = hotel.getName();this.address = hotel.getAddress();this.price = hotel.getPrice();this.score = hotel.getScore();this.brand = hotel.getBrand();this.city = hotel.getCity();this.starName = hotel.getStarName();this.business = hotel.getBusiness();this.location = hotel.getLatitude() + ", " + hotel.getLongitude();this.pic = hotel.getPic();}
}

 Service修改

    private PageResult handleResponse(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遍历List<HotelDoc> hotels=new ArrayList<>();for (SearchHit hit : hits) {//获取文档sourceString json = hit.getSourceAsString();//反序列化HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);//获取排序值Object[] sortValues = hit.getSortValues();if(sortValues.length>0){Object sortValue = sortValues[0];hotelDoc.setDistance(sortValue);}hotels.add(hotelDoc);}return new PageResult(total,hotels);}

这里应该成功显示距离附近酒店以及距离了,但是我的电脑获取不到位置。 

  黑马旅游案例——广告置顶

 DTO修改

在HotelDoc中添加一个新字段

private Boolean isAD;

ES数据修改

 Service层修改

 

    private static void buildBasicQuery(RequestParams requestParams, SearchRequest request) {//1.构建BooleanQueryBoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//关键字搜索String key= requestParams.getKey();if(key==null||"".equals(key)){  //没有查询内容时直接查询全部boolQuery.must(QueryBuilders.matchAllQuery());}else {boolQuery.must(QueryBuilders.matchQuery("all", key));}//城市条件if(requestParams.getCity()!=null&&!requestParams.getCity().equals("")){boolQuery.filter(QueryBuilders.termQuery("city", requestParams.getCity()));}//品牌条件if(requestParams.getBrand()!=null&&!requestParams.getBrand().equals("")){boolQuery.filter(QueryBuilders.termQuery("brand", requestParams.getBrand()));}//星级条件if(requestParams.getStarName()!=null&&!requestParams.getStarName().equals("")){boolQuery.filter(QueryBuilders.termQuery("starName", requestParams.getStarName()));}//价格条件if(requestParams.getMinPrice()!=null&& requestParams.getMaxPrice()!=null){boolQuery.filter(QueryBuilders.rangeQuery("price").gte(requestParams.getMinPrice()).lte(requestParams.getMaxPrice()));}//2.算分控制FunctionScoreQueryBuilder functionScoreQueryBuilder =QueryBuilders.functionScoreQuery(//原始查询,相关性算分的查询boolQuery,//function score的数组new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{//其中的一个function score 元素new FunctionScoreQueryBuilder.FilterFunctionBuilder(//过滤条件QueryBuilders.termQuery("isAD",true),//算分函数ScoreFunctionBuilders.weightFactorFunction(10))});request.source().query(functionScoreQueryBuilder);}

最终查询时就可以看见置顶的广告了

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/79462.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Transformer1.0-预热

一.Encoder encoder:译为编码器&#xff0c;负责将输入序列压缩成指定长度的向量&#xff0c;这个向量就可以堪称是这个序列的语义。然后可进行编码或特征提取等操作 在transformer中encoder由6个相同的层组成&#xff0c;每个层包含 Multi-Head Self-AttentionPosition-Wise …

【Vue】Parsing error: No Babel config file detected for ... vue

报错 Parsing error: No Babel config file detected for E:\Study\Vue网站\实现防篡改的水印\demo02\src\App.vue. Either disable config file checking with requireConfigFile: false, or configure Babel so that it can find the config files.             …

GD32F103VE侵入事件

GD32F103VE的TAMPER引脚(PC13)&#xff0c;当PC13输入低电平时&#xff0c;会产生一个侵入检测事件。它会将所有“数据备份寄存器”内容清除。 这个功能有什么用&#xff1f; 一是防止被人开壳&#xff0c;抄袭。二是自毁功能。 直奔主题&#xff0c;多一句就是浪费时间。测试…

Docker快速入门笔记

Docker快速入门 前言 当今软件开发领域的一股热潮正在迅速兴起&#xff0c;它融合了便捷性、灵活性和可移植性&#xff0c;让开发者们欣喜若狂。它就是 Docker&#xff01;无论你是一个初学者&#xff0c;还是一位经验丰富的开发者&#xff0c;都不能错过这个引领技术浪潮的工…

Elastic的下载

文章目录 ElasticSearch的下载扩展1&#xff08;ElasticSearch 与 JDK 版本 适配&#xff09;扩展2&#xff08;访问 http://192.168.1.200:9200 没有显示信息&#xff09;扩展3&#xff08;免密登录&#xff09; ElasticSearch的下载 官方下载网址&#xff1a;https://www.el…

maven install命令:将包安装在本地仓库,供本地的其它工程或者模块依赖

说明 有时候&#xff0c;自己本地的maven工程依赖于本地的其它工程&#xff0c;或者manven工程中的一个模块依赖于另外的模块&#xff0c;可以执行maven的install命令&#xff0c;将被依赖的包安装在maven本地仓库。 示例 一个工程包含几个模块&#xff0c;模块之间存在依赖…

码云 Gitee + Jenkins 配置教程

安装jdk 安装maven 安装Jenkins https://blog.csdn.net/minihuabei/article/details/132151292?csdn_share_tail%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22132151292%22%2C%22source%22%3A%22minihuabei%22%7D 插件安装 前往 Manage Jen…

解决Vs Code工具开发时 保存React文件时出现乱码情况

Vs Code工具开发时 保存React文件时出现乱码情况 插件库搜索:JS-CSS-HTML Formatter 把这个插件禁用或者卸载就解决保存时出现乱码的问题了; 如果没有解决,再看下面方案! 出现乱码问题通常是因为文件的编码格式不正确。您可以尝试以下解决方法&#xff1a; 确认文件编码格式&a…

Visual Studio 2019 实用功能设置(背景颜色,代码字体及行号设置)

前言 Visual Studio 2019 安装包的下载教程、安装教程 教程 博主博客链接&#xff1a;https://blog.csdn.net/m0_74014525 关注博主&#xff0c;后期持续更新系列文章 系列文章 第一篇&#xff1a;Visual Studio 2019 详细安装教程&#xff08;图文版&#xff09; 第二篇&…

在win10, win11 家庭版中安装远程桌面服务

win10&#xff0c; win11 家庭版中提供远程桌面服务 简介 在windows家庭版中&#xff0c;是不提供远程桌面服务的&#xff0c;你没有办法使用远程桌面连接到windows家庭版中。 当然&#xff0c; 你可用升级windows 版本到专业版&#xff0c;这样就可用享受到windows自带的远程…

基于ARM+FPGA (STM32+ Cyclone 4)的滚动轴承状态监测系统

状态监测系统能够在故障早期及时发现机械设备的异常状态&#xff0c;避免故障的 进一步恶化造成不必要的损失&#xff0c;滚动轴承是机械设备的易损部件&#xff0c;本文对以滚动 轴承为研究对象的状态监测系统展开研究。现有的监测技术多采用定时上传监 测数据&#xff0c;…

自定义elementui的主题

通常情况下&#xff0c;我们使用elementui框架的时候默认组件的主题都是白色的&#xff0c;比如&#xff1a; 但是如果想自定义主题&#xff0c;改变主题颜色&#xff0c;以及各种默认颜色&#xff0c;其实也不难&#xff1a; 配置默认主题&#xff0c;选好后点击下载 在vu…

重磅!百度再放大招,文心大模型3.5三大维度、20项指标遥遥领先

近日&#xff0c;清华大学新闻与传播学院沈阳团队发布《大语言模型综合性能评估报告》&#xff08;下文简称“报告”&#xff09;&#xff0c;报告显示百度文心一言在三大维度20项指标中综合评分国内第一&#xff0c;超越ChatGPT&#xff0c;其中中文语义理解排名第一&#xff…

JVM基础篇-StringTable

StringTable 特性 常量池中的字符串仅是符号&#xff0c;第一次用到时才变为对象 利用串池的机制&#xff0c;来避免重复创建字符串对象 字符串变量拼接的原理是 StringBuilder &#xff08;1.8&#xff09; 字符串常量拼接的原理是编译期优化 可以使用 intern 方法&#…

VSCode C/C++ 分目录编译配置

分目录编译配置记录 launch.json文件 注释处为修改内容 {// 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。// 欲了解更多信息&#xff0c;请访问: https://go.microsoft.com/fwlink/?linkid830387"version": "0.2.0","configur…

uniapp两个单页面之间进行传参

1.单页面传参&#xff1a;A --> B url: .....?code JSON.stringify(param), 2.单页面传参B–>Auni.$emit() uni.$on()

shell 入门练习小记

一、hello world #!/bin/bash echo "Hello World !"#! 为约定的标记&#xff0c;告诉系统这个脚本需要什么解释器执行&#xff0c;后接绝对路径 /bin/bash 表示期望 bash去解析并运行shell echo用于向窗口输出文本 chmod x ./test.sh #给脚本赋执行权限 ./test.sh …

Android性能优化—数据结构优化

优化数据结构是提高Android应用性能的重要一环。在Android开发中&#xff0c;ArrayList、LinkedList和HashMap等常用的数据结构的正确使用对APP性能的提升有着重大的影响。 一、ArrayList ArrayList内部使用的是数组&#xff0c;默认大小10&#xff0c;当数组长度不足时&…

【Linux命令详解 | cp命令】Linux系统中用于复制文件或目录的命令

文章标题 简介参数列表二&#xff0c;使用介绍1. 复制单个文件2. 复制多个文件3. 复制目录4. 保留文件属性5. 创建链接6. 强制覆盖7. 显示复制进度8. 创建备份9. 只有当源文件比目标文件新时才复制10. 复制链接文件 总结 简介 cp命令在Linux系统中用于复制文件或目录。其功能强…

通用人工智能操作系统

随着科技的飞速发展&#xff0c;人工智能已经成为了当今世界最热门的技术领域之一。从智能手机、自动驾驶汽车到智能家居系统&#xff0c;人工智能技术已经渗透到了我们生活的方方面面。然而&#xff0c;尽管人工智能在很多领域取得了显著的成果&#xff0c;但它仍然存在一些局…