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 Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

SpringBoot整合Dubbo+ZK注册失败的坑及解决

《SpringBoot整合Dubbo+ZK注册失败的坑及解决》使用Dubbo框架时,需在公共pom添加依赖,启动类加@EnableDubbo,实现类用@DubboService替代@Service,配... 目录1.先看下公共的pom(maven创建的pom工程)2.启动类上加@EnableDubbo3.实

SpringBoot整合(ES)ElasticSearch7.8实践

《SpringBoot整合(ES)ElasticSearch7.8实践》本文详细介绍了SpringBoot整合ElasticSearch7.8的教程,涵盖依赖添加、客户端初始化、索引创建与获取、批量插... 目录SpringBoot整合ElasticSearch7.8添加依赖初始化创建SpringBoot项

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种