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中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时