SpringBoot2.x RestClient 操作ElasticSearch 7.x

2024-01-09 21:08

本文主要是介绍SpringBoot2.x RestClient 操作ElasticSearch 7.x,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SpringBoot2.x RestClient 操作ElasticSearch 7.x

  • 本地环境
  • ES新版和老板差异
    • 7.6.2 版本
    • 老版本
  • 使用 RestClient
    • 导入依赖
    • yml配置
    • rest新建索引文档
    • 判断索引是否存在
    • 查找
    • 高亮

本地环境

Spring Boot 2.2.6
Elasticsearch 7.6.2
写这个文章的原因是
“The well known TransportClient is deprecated as of Elasticsearch 7 and will be removed in Elasticsearch 8. (see the Elasticsearch documentation). Spring Data Elasticsearch will support the TransportClient as long as it is available in the used Elasticsearch version.
We strongly recommend to use the High Level REST Client instead of the TransportClient.”
但是网上关于RestClient的资料却很少

ES新版和老板差异

先说建立索引,新版不允许带有type名,我们通过代码对比,代码很简洁

7.6.2 版本

PUT http://localhost:9200/test/
{"mappings":{"properties":{"id":{"type": "long","index": true},"title":{"type": "text"}}}
}

老版本

PUT http://localhost:9200/test/
{"mappings":{"lalala":{"properties":{"id":{"type": "long","index": true},"title":{"type": "text"}}}}
}

还有常用的一点:minimum_match 新版本需要使用 minimum_should_match

使用 RestClient

导入依赖

导入依赖 这个不用说了,以前还需要Jest 包

    	<properties>.......<!--自定义elasticsearch.version版本--><!--其实不自定义默认的6.8x也可以使用我们不自定义看看连接7.6.2版本会不会出问题--><!--<elasticsearch.version>7.6.2</elasticsearch.version>--></properties><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>

yml配置

为了和老版本对比jest我没有去掉,事实上jest的uris明确表明已过时

spring:elasticsearch:jest:uris: http://localhost:9200rest:uris: http://localhost:9200

rest新建索引文档

  • 注意:代码中的JestEntity只是一个普通的实体类,你们可以自己写一个,并不是Jest包中的东西
    下面的代码我没有使用CreateIndexRequest,而是直接创建文档了
	@Autowiredprivate RestHighLevelClient restClient;@Testpublic void testRestCreate(){JestEntity entity = new JestEntity();entity.setId(1);entity.setTitle("我是文章标题");ObjectMapper mapper=new ObjectMapper();String source = mapper.writeValueAsString(entity);// 1. 建立IndexRequest//注意这里的type 事实上在es7中就是文档,type已经被弃用//这里的source是个json,我懒得引入fastjson用jackson做了//如果在xml修改了es版本号,这里可以只写2个变量,index和idIndexRequest request = new IndexRequest("test", "_doc", "1").source(source, XContentType.JSON).setRefreshPolicy(IMMEDIATE);//发送请求try {IndexResponse res = restClient.index(request, RequestOptions.DEFAULT);System.out.println(res);} catch (IOException e) {e.printStackTrace();}// 异步方式/*ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {@Overridepublic void onResponse(IndexResponse indexResponse) {System.out.println("调用完成");System.out.println(indexResponse);}@Overridepublic void onFailure(Exception e) {e.printStackTrace();}};restClient.indexAsync(request,RequestOptions.DEFAULT,listener);*/}

判断索引是否存在

	@Testpublic void testRestExists(){GetIndexRequest request = new GetIndexRequest("test");//注意 我这里用的是indices方法,故意换个方法,让大家了解一下CreateIndexResponse res = restClient.indices().exists(request,RequestOptions.DEFAULT);System.out.println(res);}

查找

	@Testpublic void testRestSearch(){SearchRequest searchRequest = new SearchRequest("test");//ES7 不需要types 是为了兼容老版本的东西//如果写了会抛异常并且卡死在这//searchRequest.types("_doc"); SearchSourceBuilder searchSource = new SearchSourceBuilder();//匹配所有//searchSource.query(QueryBuilders.matchAllQuery());//只匹配titlesearchSource.query(QueryBuilders.matchQuery("title", "文章"));searchRequest.source(searchSource);try {SearchResponse res = restClient.search(searchRequest, RequestOptions.DEFAULT);System.out.println(res);} catch (IOException e) {e.printStackTrace();}}

高亮

highlightBuilder.field 新版本必须设置,否则会获取不到高亮内容

@Testpublic void testRestSearch() throws IOException {//创建搜索请求SearchRequest searchRequest = new SearchRequest("Hoola");//searchRequest.types("_doc"); ES7 不需要 是为了兼容老版本的东西//创建搜索源SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//创建高亮并设置fieldHighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.field("tag").field("title");//不设置会获取不到highlightBuilder.preTags("<span style='color:red'>");highlightBuilder.postTags("</span>");//设置搜索条件,故意写的复杂一些,让你们看看restClient的搜索searchSourceBuilder.query(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("tag", "抠脚 大汉")).should(QueryBuilders.matchQuery("title", "蛇皮 香蕉 象拔蚌")).minimumShouldMatch(1)).highlighter(highlightBuilder).from(0).size(10);//绑定搜索源searchRequest.source(searchSourceBuilder);SearchResponse res = restClient.search(searchRequest, RequestOptions.DEFAULT);//获取内容for (SearchHit hit:res.getHits().getHits()){Map<String, Object> sourceAsMap = hit.getSourceAsMap();Map<String, HighlightField> highlightFields = hit.getHighlightFields();//判断高亮是否存在,存在就替换到map中去if (highlightFields.get("title")!=null){sourceAsMap.put("title",highlightFields.get("title").fragments());}if (highlightFields.get("tag")!=null){sourceAsMap.put("tag",highlightFields.get("tag").fragments());}JestEntity jestEntity = new JestEntity();try {//map数据迁移到实体对象里。BeanUtils.populate(jestEntity, sourceAsMap);System.out.println(jestEntity);} catch (IllegalAccessException|InvocationTargetException e) {e.printStackTrace();} }}

这篇关于SpringBoot2.x RestClient 操作ElasticSearch 7.x的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/588435

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

SpringBoot整合liteflow的详细过程

《SpringBoot整合liteflow的详细过程》:本文主要介绍SpringBoot整合liteflow的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...  liteflow 是什么? 能做什么?总之一句话:能帮你规范写代码逻辑 ,编排并解耦业务逻辑,代码