Springboot 整合 Elasticsearch(三):使用RestHighLevelClient操作ES ①

本文主要是介绍Springboot 整合 Elasticsearch(三):使用RestHighLevelClient操作ES ①,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

📁 前情提要:

Springboot 整合 Elasticsearch(一):Linux下安装 Elasticsearch 8.x

Springboot 整合 Elasticsearch(二):使用HTTP请求来操作ES

目录

一、Springboot 整合 Elasticsearch

1、pom.xml 中添加依赖

2、application.yml 中添加配置项

3、RestHighLevelClient API介绍

3.1、连接配置类

3.2、检查索引是否存在

3.2、创建索引

3.3、删除索引

3.4、增加文档

3.5、按主键更新文档内容

3.6、按主键删除文档内容

3.7、批量添加文档


一、Springboot 整合 Elasticsearch

1、pom.xml 中添加依赖

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

2、application.yml 中添加配置项

spring:elasticsearch:rest:uris: 192.168.1.250:9200

3、RestHighLevelClient API介绍

3.1、连接配置类

@Component
public class EsConfig {@Value("${spring.elasticsearch.rest.uris}")private String uris;/*** 高版本客户端** @return*/@Beanpublic RestHighLevelClient restHighLevelClient() {String[] split = uris.split(",");HttpHost[] httpHostArray = new HttpHost[split.length];for (int i = 0; i < split.length; i++) {String item = split[i];httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");}// 创建RestHighLevelClient客户端return new RestHighLevelClient(RestClient.builder(httpHostArray));}
}

3.2、检查索引是否存在

    @Testpublic void checkIndex() {try {String indexName = "forest";boolean exists = esConfig.restHighLevelClient().indices().exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT);System.out.println("exists:" + exists);} catch (IOException e) {e.printStackTrace();}}

3.2、创建索引

    @Testpublic void createIndex() {try {// 创建名为“森林”的索引String indexName = "forest";if (checkIndex(indexName)) {log.info("已存在名为{}的索引", indexName);return;}CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);CreateIndexResponse createIndexResponse = esConfig.restHighLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT);System.out.println("已创建索引:" + createIndexResponse.index());} catch (IOException e) {e.printStackTrace();}}public boolean checkIndex(String indexName) {boolean exists = false;try {exists = esConfig.restHighLevelClient().indices().exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}return exists;}

3.3、删除索引

    @Testpublic void deleteIndex() {String indexName = "forest";DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);// 发送delete请求try {AcknowledgedResponse response = esConfig.restHighLevelClient().indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);System.out.println("是否已删除:" + response.isAcknowledged());} catch (IOException e) {e.printStackTrace();}}

3.4、增加文档

    @Testpublic void createDoc() {try {String indexName = "forest";ForestDoc forestDoc = new ForestDoc();forestDoc.setId(001L).setTitle("枫树").setImages("http://fengshu.jpg").setPrice(300.00).setInventory(600);// 创建索引请求对象IndexRequest indexRequest = new IndexRequest(indexName);indexRequest.id(forestDoc.getId().toString());indexRequest.source(JSON.toJSONString(forestDoc), XContentType.JSON);// 设置数据刷新策略indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);IndexResponse index = esConfig.restHighLevelClient().index(indexRequest, RequestOptions.DEFAULT);System.out.println("状态:" + index.status().getStatus());} catch (IOException e) {e.printStackTrace();}}

 ⚠️​​​​​RefreshPolicy 刷新策略,是WriteRequest接口中的一个内部枚举
 ① IMMEDIATE:
    请求向ElasticSearch提交了数据,立即进行数据刷新,然后再结束请求。
    优点:实时性高、操作延时短。
    缺点:资源消耗高。
 ② WAIT_UNTIL:
    请求向ElasticSearch提交了数据,等待数据完成刷新,然后再结束请求。
    优点:实时性高、操作延时长。
    缺点:资源消耗低。
 ③ NONE:
    默认策略。
    请求向ElasticSearch提交了数据,不关系数据是否已经完成刷新,直接结束请求。
    优点:操作延时短、资源

3.5、按主键更新文档内容

修改 id 为 2 的 images字段内容

    @Testpublic void updateDocById() {try {String indexName = "forest";String id = "2";UpdateRequest updateRequest = new UpdateRequest(indexName, id);Map<String, Object> map = new HashMap<>();map.put("images", "http://baihuashu.jpg");updateRequest.doc(map);UpdateResponse update = esConfig.restHighLevelClient().update(updateRequest, RequestOptions.DEFAULT);System.out.println("状态:" + update.status().getStatus());} catch (IOException e) {e.printStackTrace();}}

3.6、按主键删除文档内容

    @Testpublic void deleteDocById() {String indexName = "forest";String id = "5";DeleteRequest deleteRequest = new DeleteRequest(indexName,id);try {DeleteResponse delete = esConfig.restHighLevelClient().delete(deleteRequest, RequestOptions.DEFAULT);System.out.println("状态:" + delete.status().getStatus());} catch (IOException e) {e.printStackTrace();}}

3.7、批量添加文档

    @Testpublic void batchCreateDoc() {try {String indexName = "forest";List<ForestDoc> list = new ArrayList<>();ForestDoc forestDoc = new ForestDoc();forestDoc.setId(6L).setTitle("批量_柏树").setImages("http://baishu.jpg").setPrice(1100.00).setInventory(1200);list.add(forestDoc);ForestDoc forestDoc2 = new ForestDoc();forestDoc2.setId(7L).setTitle("批量_苹果树").setImages("http://pingguoshu.jpg").setPrice(1200.00).setInventory(1300);list.add(forestDoc2);ForestDoc forestDoc3 = new ForestDoc();forestDoc3.setId(8L).setTitle("批量_海棠树").setImages("http://haitangshu.jpg").setPrice(1300.00).setInventory(1400);list.add(forestDoc3);//批量导入BulkRequest bulk = new BulkRequest(indexName);for (ForestDoc doc : list) {IndexRequest indexRequest = new IndexRequest();indexRequest.id(doc.getId().toString());indexRequest.source(JSON.toJSONString(doc), XContentType.JSON);bulk.add(indexRequest);}BulkResponse bulkResponse = esConfig.restHighLevelClient().bulk(bulk, RequestOptions.DEFAULT);System.out.println("状态:" + bulkResponse.status().getStatus());} catch (IOException e) {e.printStackTrace();}}


这篇关于Springboot 整合 Elasticsearch(三):使用RestHighLevelClient操作ES ①的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

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. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Spring事务传播机制最佳实践

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

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.