目录

初始化javaRestClient

RestClient操作索引库

RestClient操作文档

排序,高亮,分页,复合查询

Boolean Query

Function Query


初始化javaRestClient

引入es的RestHiggLeveClient依赖

<!-- elasticsearch--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId></dependency>

因为SpringBoot默认的ES版本是7.6.2,所以需要覆盖默认的ES版本:

<properties><elasticsearch.version>7.12.1</elasticsearch.version></properties>

初始化RestClient

@SpringBootApplication
public class HotelDemoApplication {public static void main(String[] args) {SpringApplication.run(HotelDemoApplication.class, args);}@Beanpublic RestHighLevelClient client() {return new RestHighLevelClient(RestClient.builder(//es集群地址HttpHost.create("http://192.168.80.130:9200"),HttpHost.create("http://192.168.80.131:9200")));}
}

RestClient操作索引库

  • 创建索引库:client.indices().create()
  • 删除索引库:client.indices().delete()
  • 校验索引库是否存在:client.indices().exists()

创建索引库,例:

import org.elasticsearch.client.indices.CreateIndexRequest;@Testvoid createhotelindex() throws IOException {//创建request对象CreateIndexRequest request = new CreateIndexRequest("索引库");//准备请求参数:DSL语句request.source("DSL语句", XContentType.JSON);//发起请求client.indices().create(request, RequestOptions.DEFAULT);}

RestClient操作文档

  1. 添加文档:client.index()
  2. 查询文档:client.get()
  3. 删除文档:client.delete()
  4. 修改文档:
  • 全量修改:client.index()
  • 增量修改:client.update()

添加文档

/*** 将数据库中的数据添加es索引库*/@Testvoid documentaddtest() throws IOException {Hotel hotel = iHotelService.getById(36934L);HotelDoc hotelDoc = new HotelDoc(hotel);IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);client.index(request,RequestOptions.DEFAULT);}

批量添加文档

@Testvoid documentBatchtest() throws IOException {//准备对象BulkRequest request = new BulkRequest();// 查询数据库中的数据List<Hotel> hotels = iHotelService.list();//通过Steam流添加多条数据hotels.stream().map(item -> {HotelDoc hotelDoc = new HotelDoc(item);request.add(new IndexRequest("hotel").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc),XContentType.JSON));return item;}).collect(Collectors.toList());//发起请求client.bulk(request,RequestOptions.DEFAULT);}

查询文档

@Testvoid documentgettest() throws IOException {GetRequest request = new GetRequest("索引库","id");GetResponse response = client.get(request, RequestOptions.DEFAULT);//获取源数据String json = response.getSourceAsString();//反序列化为对象HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);System.out.println(hotelDoc);}

删除文档

@Testvoid documentdeletetest() throws IOException {DeleteRequest request = new DeleteRequest("索引库","id");client.delete(request,RequestOptions.DEFAULT);}

增量修改文档

@Testvoid documentupdatetest() throws IOException {UpdateRequest request = new UpdateRequest("hotel","36934");Map<String,Object> map = new HashMap<>();map.put("starName","三钻");map.put("price",337);request.doc(map);client.update(request,RequestOptions.DEFAULT);}

排序,高亮,分页,复合查询

解析文档数据

    void resulthits(SearchResponse response) {//获取数据条数long total = response.getHits().getTotalHits().value;//获取文档SearchHit[] hits = response.getHits().getHits();HotelDoc hotelDoc = new HotelDoc();for (SearchHit searchHit: hits) {//获取文档sourceString json = searchHit.getSourceAsString();//反序列化为对象hotelDoc = JSON.parseObject(json, HotelDoc.class);//获取文档高亮数据Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();//判断是否做高亮处理if (!(CollectionUtils.isEmpty(highlightFields))){//获取字段名为name的高亮数据HighlightField name = highlightFields.get("name");//判断是否高亮name字段if (name != null){//获取高亮值Text[] fragments = name.getFragments();//覆盖原始的name字段hotelDoc.setName(fragments[0].toString());}}System.out.println(hotelDoc);}}

Boolean Query

@Testvoid testbool() throws IOException {//准备request,连接索引库SearchRequest request = new SearchRequest("hotel");BoolQueryBuilder queryBuilder = new BoolQueryBuilder();//TODO 查询坐标在31.21,121.5附件10km的价格不高于400的如家酒店的前五家酒店,且对距离做升序排序queryBuilder.must(QueryBuilders.termQuery("brand","如家"))//查询brand为如家品牌.mustNot(QueryBuilders.rangeQuery("price").gte(400))//;//price不高于400.filter(QueryBuilders//过滤.geoDistanceQuery("location")//字段名.point(31.21,121.5)//经纬度 先纬度后经度.distance(10, DistanceUnit.KILOMETERS));//前:半径长度,后:单位km//准备dsl语句request.source().query(queryBuilder)//查询//高亮处理.highlighter(new HighlightBuilder().requireFieldMatch(false).field("name").preTags("<em>").postTags("</em>"))//分页处理.from(0)//分页起始位置.size(5)//每页的数量.sort(SortBuilders.geoDistanceSort("location",new GeoPoint(31.21,121.5))//字段名 ,中心点坐标.order(SortOrder.ASC)//升序排序.unit(DistanceUnit.KILOMETERS));//单位KM//发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);//解析文档数据resulthits(response);}

Function Query

@Testvoid search() throws IOException {SearchRequest requset = new SearchRequest("hotel");//算分控制//TODO 给isAD字段为true的酒店的算分结果都乘10FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(//原始查询QueryBuilders.matchQuery("all", "速8"),//function score数组new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{//其中的一个function score的元素new FunctionScoreQueryBuilder.FilterFunctionBuilder(//过滤条件QueryBuilders.termQuery("isAD",true),//算分函数(规则)ScoreFunctionBuilders.weightFactorFunction(10))});requset.source().query(functionScoreQuery);//分页requset.source().from((0)).size(5);SearchResponse response = client.search(requset, RequestOptions.DEFAULT);//解析响应resulthits(response);}

RestClient相关推荐

  1. 神器:REST测试工具[wiztools.org restclient]客户端Jar依赖Java安装环境

    背景 使用Spring Boot开发集群应用,架构风格启用RestFul之后表单Post请求无法Url测试,必须使用专用工具测试 主题 经过亲身感受,测试发现最靠谱的工具非[wiztools.org ...

  2. 使用Wisdom RESTClient如何在Linux和Mac上获取测试报告和API文档?

    使用Wisdom RESTClient自动化测试REST API,生成REST API文档, 需要先执行命令java -jar restclient-1.2.jar启动Wisdom RESTClien ...

  3. restclient发送json_怎么使用restclient来发送post请求参数

    满意答案 我喜欢使用 restclient 来测试我的 REST 风格的应用程序.一般我就是用GET方法,今天用到了POST方法.POST传递参数应该放在body里面,对长度没有限制.不像GET对UR ...

  4. Wisdom RESTClient支持自动化测试并可以生成API文档

    Wisdom REST Client V1.2 支持自动化测试RESTful API并生成精美的测试报告,同时基于历史数据自动生成精美的RESTful API文档. 工具地址:https://gith ...

  5. RESTClient 用法

    为什么80%的码农都做不了架构师?>>>    Wisdom RESTClient 一款自动化测试REST API的工具,它可以自动化测试RESTful API并生成精美的测试报告, ...

  6. http接口测试工具——RESTClient

    2019独角兽企业重金招聘Python工程师标准>>> WizTools.org RESTClient is a Java Swing application for testing ...

  7. RESTful测试工具RESTClient

    1.简介 RESTClient是一个用于测试RESTful Web服务的客户端, 是用Java Swing编写的基于Http协议的接口测试工具, 它可以向服务器发送各种Http请求,并显示服务器响应. ...

  8. WebFlux响应式编程基础之 6 webflux客户端声明式restclient框架开发讲解

    第6章 webflux客户端声明式 restclient框架开发讲解 看不懂,为什么看不懂? 写方法最主要考虑输入与输出 Feign Retrofit 框架 6-1 框架效果介绍 6-2 设计思路 6 ...

  9. 使用火狐的restclient发送http接口post及get请求

    1.在firefox安装restclient插件,具体参照http://jingyan.baidu.com/article/1876c8529b07e3890b137623.html: -.发送pos ...

  10. RestClient使用

    1.在火狐浏览器里下载restclient插件 2.输入地址和请求参数 3.单击send 如图: 4.感悟在使用的过程中因为我没有设置Header,所有总是报400 bad request.期间有好几 ...

最新文章

  1. html form提交前验证,form表单提交前验证实现方法
  2. Word 2010中利用尾注添加参考文献(论文必备)
  3. python——迭代器
  4. adb 命令 pc端 复制粘贴 文本到android设备
  5. [渝粤教育] 中国地质大学 自动控制原理 复习题 (2)
  6. __attribute__ 之weak,alias属性
  7. D3 interpolate
  8. QT QDir(获取当前路径下的所有文件)
  9. 前端实习一个多月总结
  10. linux系统自动获取ip地址,Linux系统怎么自动获取ip地址用什么命令
  11. iOS深拷贝和浅拷贝
  12. 飞龙在天-中国新战机将在歼11基础上腾飞
  13. ANTELOPE WASHBASIN | ANTELOPE 洗脸盆
  14. UVA 10815 安迪的第一个字典
  15. 好心情:22个表达好心情的经典句子,送给抑郁焦虑的你
  16. stl文件转stp (二次开发)
  17. 如何查看apk安装包源代码??Android反编译apk,解包,打包,签名一体化实测 ,修改图片音频软件名称版本号等入门
  18. 谈谈唯一约束和唯一索引
  19. 在手机上安装Ubuntu(Termux)
  20. 用python解决选择困难症

热门文章

  1. VirtualBox下安装Windows Server 2008
  2. eclipse linux 中文,Eclipse (简体中文)
  3. 计算机英语知识竞赛题库,大学生计算机基础知识竞赛题库_大学生计算机基础知识竞赛试题附答案...
  4. 百度螺旋桨PaddleHelix论道“AI+生物计算”,加速推进多维价值释放
  5. grub4dos初级教程
  6. Linux系统怎么安装谷歌拼音,linux下安装google拼音输入法
  7. bootcamp opencore_macbook pro用启动转换助理(bootcamp)安装win10踩的坑 | ZPY博客
  8. erp采购总监个人总结_ERP采购总监总结
  9. 【硬见小百科】数字万用表的工作原理
  10. 计算机显示器刷新率怎么调,电脑显示器刷新率如何设置,免费教你如何快手设置刷新率...