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 Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

RedHat运维-Linux文本操作基础-AWK进阶

你不用整理,跟着敲一遍,有个印象,然后把它保存到本地,以后要用再去看,如果有了新东西,你自个再添加。这是我参考牛客上的shell编程专项题,只不过换成了问答的方式而已。不用背,就算是我自己亲自敲,我现在好多也记不住。 1. 输出nowcoder.txt文件第5行的内容 2. 输出nowcoder.txt文件第6行的内容 3. 输出nowcoder.txt文件第7行的内容 4. 输出nowcode

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

22.手绘Spring DI运行时序图

1.依赖注入发生的时间 当Spring loC容器完成了 Bean定义资源的定位、载入和解析注册以后,loC容器中已经管理类Bean 定义的相关数据,但是此时loC容器还没有对所管理的Bean进行依赖注入,依赖注入在以下两种情况 发生: 、用户第一次调用getBean()方法时,loC容器触发依赖注入。 、当用户在配置文件中将<bean>元素配置了 lazy-init二false属性,即让

21.手绘Spring IOC运行时序图

1.再谈IOC与 DI IOC(lnversion of Control)控制反转:所谓控制反转,就是把原先我们代码里面需要实现的对象创 建、依赖的代码,反转给容器来帮忙实现。那么必然的我们需要创建一个容器,同时需要一种描述来让 容器知道需要创建的对象与对象的关系。这个描述最具体表现就是我们所看到的配置文件。 DI(Dependency Injection)依赖注入:就是指对象是被动接受依赖类

20.Spring5注解介绍

1.配置组件 Configure Components 注解名称说明@Configuration把一个类作为一个loC容 器 ,它的某个方法头上如果注册7@Bean , 就会作为这个Spring容器中的Bean@ComponentScan在配置类上添加@ComponentScan注解。该注解默认会扫描该类所在的包下所有的配置类,相当于之前的 <context:component-scan>@Sc

19.手写Spring AOP

1.Spring AOP顶层设计 2.Spring AOP执行流程 下面是代码实现 3.在 application.properties中增加如下自定义配置: #托管的类扫描包路径#scanPackage=com.gupaoedu.vip.demotemplateRoot=layouts#切面表达式expression#pointCut=public .* com.gupaoedu

17.用300行代码手写初体验Spring V1.0版本

1.1.课程目标 1、了解看源码最有效的方式,先猜测后验证,不要一开始就去调试代码。 2、浓缩就是精华,用 300行最简洁的代码 提炼Spring的基本设计思想。 3、掌握Spring框架的基本脉络。 1.2.内容定位 1、 具有1年以上的SpringMVC使用经验。 2、 希望深入了解Spring源码的人群,对 Spring有一个整体的宏观感受。 3、 全程手写实现SpringM

16.Spring前世今生与Spring编程思想

1.1.课程目标 1、通过对本章内容的学习,可以掌握Spring的基本架构及各子模块之间的依赖关系。 2、 了解Spring的发展历史,启发思维。 3、 对 Spring形成一个整体的认识,为之后的深入学习做铺垫。 4、 通过对本章内容的学习,可以了解Spring版本升级的规律,从而应用到自己的系统升级版本命名。 5、Spring编程思想总结。 1.2.内容定位 Spring使用经验