Elasticsearch8.x版本Java客户端Elasticsearch Java API Client中常用API练习

Es的java API客户端

在Es7.15版本之后,es官方将它的高级客户端RestHighLevelClient标记为弃用状态。同时推出了全新的java API客户端Elasticsearch Java API Client,该客户端也将在Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。

Elasticsearch Java API Client支持除Vector title search API和Find structure API之外的所有Elasticsearch API。且支持所有API数据类型,并且不再有原始JSON Value属性。它是针对Elasticsearch8.0及之后版本的客户端。

maven中引入依赖坐标

  <dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>8.12.2</version></dependency><dependency><groupId>co.elastic.clients</groupId><artifactId>elasticsearch-java</artifactId><version>8.12.2</version><exclusions><exclusion><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId></exclusion></exclusions></dependency>
  • 创建连接
@Beanpublic ElasticsearchClient elasticsearchClient(@Value("${elasticsearch.xxxx}") String serverUrl,@Value("${elasticsearch.xxxxx}") String apiKey) {RestClient restClient = RestClient.builder(HttpHost.create(serverUrl)).setDefaultHeaders(new Header[]{new BasicHeader("Authorization", "ApiKey " + apiKey),}).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());return new ElasticsearchClient(transport);}
  • 索引index
  @Testpublic void create() throws IOException {// 创建低级客户端RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();// 使用Jackson映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建API客户端ElasticsearchClient client = new ElasticsearchClient(transport);// 创建索引CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("user_test"));// 响应状态Boolean acknowledged = createIndexResponse.acknowledged();System.out.println("索引操作 = " + acknowledged);// 关闭ES客户端transport.close();restClient.close();}
  • 查询索引
@Testpublic void query() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost",9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 查询索引GetIndexResponse getIndexResponse = client.indices().get(e -> e.index("user_test"));System.out.println("getIndexResponse.result() = " + getIndexResponse.result());System.out.println("getIndexResponse.result().keySet() = " + getIndexResponse.result().keySet());transport.close();restClient.close();} 

如果查询的index不存在会在控制台抛出index_not_found_exception

  • 删除索引
 @Testpublic void delete() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 删除索引DeleteIndexResponse deleteIndexResponse = client.indices().delete(e -> e.index("user_test"));System.out.println("删除操作 = " + deleteIndexResponse.acknowledged());transport.close();restClient.close();}

文档document的操作

  • 添加document
@Testpublic void addDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 向user对象中添加数据User user = new User("java客户端", "男", 18);// 向索引中添加数据CreateResponse createResponse = client.create(e -> e.index("user_test").id("1001").document(user));System.out.println("createResponse.result() = " + createResponse.result());transport.close();restClient.close();}

注:index中参数为文档所属的索引名,id中参数为当文档的id,document为文档数据,新版本支持直接传入java对象。

  • 查询document
 @Testpublic void queryDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 构建请求GetResponse<User> getResponse = client.get(e -> e.index("user_test").id("1001"), User.class);System.out.println("getResponse.source().toString() = " + getResponse.source().toString());transport.close();restClient.close();}

注:如果查不到控制台抛出NullPointerException

  • 修改document
@Testpublic void modifyDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 使用map集合封装需要修改的内容Map<String, Object> map = new HashMap<>();map.put("name", "java客户端aaa");// 构建请求UpdateResponse<User> updateResponse = client.update(e -> e.index("user_test").id("1001").doc(map), User.class);System.out.println("updateResponse.result() = " + updateResponse.result());transport.close();restClient.close();}
  • 删除document
    @Testpublic void removeDocument() throws  IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 构建请求DeleteResponse deleteResponse = client.delete(e -> e.index("user_test").id("1001"));System.out.println("deleteResponse.result() = " + deleteResponse.result());transport.close();restClient.close();}
  • 批量添加document
   @Testpublic void batchAddDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 构建一个批量数据集合List<BulkOperation> list = new ArrayList<>();list.add(new BulkOperation.Builder().create(d -> d.document(new User("test2", "男", 19)).id("1002").index("user_test")).build());list.add(new BulkOperation.Builder().create(d -> d.document(new User("test3", "男", 20)).id("1003").index("user_test")).build());list.add(new BulkOperation.Builder().create(d -> d.document(new User("test4", "女", 21)).id("1004").index("user_test")).build());// 调用bulk方法执行批量插入操作BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));System.out.println("bulkResponse.items() = " + bulkResponse.items());transport.close();restClient.close();}

批量添加的核心是需要构建一个泛型为BulkOperation的ArrayList集合,实质上是将多个请求包装到一个集合中,进行统一请求,进行构建请求时调用bulk方法,实现批量添加效果。

  • 批量删除
    @Testpublic void batchDeleteDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 构建一个批量数据集合List<BulkOperation> list = new ArrayList<>();list.add(new BulkOperation.Builder().delete(d -> d.id("1002").index("user_test")).build());list.add(new BulkOperation.Builder().delete(d -> d.id("1003").index("user_test")).build());// 调用bulk方法执行批量插入操作BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));System.out.println("bulkResponse.items() = " + bulkResponse.items());transport.close();restClient.close();}
  • 全量查询
    @Testpublic void queryAllDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 全量查询SearchResponse<User> searchResponse = client.search(e -> e.index("user_test").query(q -> q.matchAll(m -> m)), User.class);HitsMetadata<User> hits = searchResponse.hits();for (Hit<User> hit : hits.hits()) {System.out.println("user = " + hit.source().toString());}System.out.println("searchResponse.hits().total().value() = " + searchResponse.hits().total().value());transport.close();restClient.close();}
  • 分页查询
@Testpublic void pagingQueryDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 分页查询SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q.matchAll(m -> m)).from(2).size(2), User.class);searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));transport.close();restClient.close();}

分页查询就是在全量查询的基础上增加了从第几条开始,每页显示几条

  • 排序查询
    @Testpublic void sortQueryDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 排序查询SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q.matchAll(m -> m)).sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc))), User.class);searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));transport.close();restClient.close();}
  • 条件查询
    @Testpublic void conditionQueryDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 条件查询SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q.matchAll(m -> m)).sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc))).source(r -> r.filter(f -> f.includes("name", "age").excludes(""))), User.class);searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));transport.close();restClient.close();}

includes是显示的字段,excludes是排除的字段

  • 组合查询
  @Testpublic void combinationQueryDocument() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 组合查询SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q.bool(b -> b.must(m -> m.match(u -> u.field("age").query(21))).must(m -> m.match(u -> u.field("sex").query("男"))).mustNot(m -> m.match(u -> u.field("sex").query("女"))))), User.class);searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));transport.close();restClient.close();}@Testpublic void combinationQueryDocument2() throws IOException {RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);// 组合查询SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q.bool(b -> b.should(h -> h.match(u -> u.field("age").query(19))).should(h -> h.match(u -> u.field("sex").query("男"))))), User.class);searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));transport.close();restClient.close();}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/746746.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java基于 Springboot+Vue 的招生管理系统,前后端分离

博主介绍&#xff1a;✌程序员徐师兄、8年大厂程序员经历。全网粉丝15w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;…

【全志H616】1 --用orangepi控制硬件

【全志H616】1 --用orangepi控制硬件 本文介绍了如歌用orangepi 控制蜂鸣器&超声波模块&#xff0c;通过键盘输入1、2、3、4来控制转动角度舵机模块&#xff1b;同时还介绍了利用全志如何配置定时器&#xff1b;以及查看H616引脚状态的命令等… 超声波模块和舵机模块的讲解…

德人合科技 | 公司办公终端、电脑文件资料 \ 数据透明加密防泄密管理软件系统

天锐绿盾是一款全面的企业级数据安全解决方案&#xff0c;它专注于为企业办公终端、电脑文件资料提供数据透明加密防泄密管理。 首页 德人合科技——www.drhchina.com 这款软件系统的主要功能特点包括&#xff1a; 1. **透明加密技术**&#xff1a; 天锐绿盾采用了透明加密技…

Android Gradle 编译过程中的优化

} 但是反射没有办法能很好的识别&#xff0c;所以如果代码中有使用反射需要自行处理&#xff0c;以免被删除。 shrink resource 功能 shrink code流程执行完后删除了无用的代码后&#xff0c;就能确认哪些资源文件没有使用&#xff0c;shrink resource流程就是确定哪些资源…

DB107-ASEMI智能LED灯具专用DB107

编辑&#xff1a;ll DB107-ASEMI智能LED灯具专用DB107 型号&#xff1a;DB107 品牌&#xff1a;ASEMI 封装&#xff1a;DB-4 正向电流&#xff08;Id&#xff09;&#xff1a;1A 反向耐压&#xff08;VRRM&#xff09;&#xff1a;1000V 正向浪涌电流&#xff1a;50A 正…

【大厂秋招高频算法】阿里秋招高频算法题汇总

欢迎关注公众号&#xff08;通过文章导读关注&#xff1a;【11来了】&#xff09;&#xff0c;及时收到 AI 前沿项目工具及新技术的推送&#xff01; 在我后台回复 「资料」 可领取编程高频电子书&#xff01; 在我后台回复「面试」可领取硬核面试笔记&#xff01; 文章导读地址…

BERT:深度学习领域中的语言理解利器

BERT&#xff1a;深度学习领域中的语言理解利器 摘要 BERT&#xff08;双向编码器表示法自转换器&#xff09;是一种领先的深度学习模型&#xff0c;它在许多语言理解任务中都显示出卓越的性能。BERT模型基于转换器编码器架构&#xff0c;并通过自监督学习在大量未标记文本数…

Windows,MacOS,Linux下载python并配置环境图文讲解

Windows 打开python官网 点击download 点击黄色按钮 另存为 打开文件 全选 配置安装路径 安装中 关闭路径长度限制 完成 验证 同时按住winr(win就是空格键左边的东西) 输入cmd 键入python,如果出现版本(红框)即安装成功 MacOS 同理打开python官网 点击最新版本 拖…

看!Chat4.0如何看待AI与光纤资源管理软件的应用结合点及价值

问&#xff1a;你好&#xff0c;AI在光纤资源管理软件中有那些应用结合点&#xff0c;请详细描述应用结合点及价值? 答&#xff1a;AI在光纤资源管理软件中的应用结合点涉及多个方面&#xff0c;它们通过智能化的手段提高资源管理的效率和准确性。以下是一些关键的应用结合点及…

ZCC1130T双节锂电池充电控制芯片

1.特点: .涓流/恒流/恒压三段式充电&#xff0c;内设充电电流可达1A; .支持对 OV 电池充电;短路保护功能; .电池正负极反接保护智能温控技术&#xff0c;充电电流会随温度升高而降低&#xff0c;在不会出现过热保护的前提下输出最大充电电流;异常电池检测; .电池平衡充电 …

Midjourney视觉垫图

https://github.com/lllyasviel/Fooocus/discussions/117https://github.com/lllyasviel/Fooocus/discussions/117掌握Midjourney的垫图技巧&#xff1a;AI绘画中的参考利器本期将深入了解AI绘画的垫图技巧&#xff0c;让作品获得更好的出图效果https://mp.weixin.qq.com/s/RS2…

unity3d Animal Controller的Animal组件中Stances,Advanced基础部分理解

Stances 立场 立场要求在动物动画控制器上的姿态动画参数。 你可以有多个运动状态,并根据当前的立场使用它们 过渡的条件是: Stance StanceID Default Stance默认姿势 如果调用函数Stance_Reset&#xff08;&#xff09;&#xff0c;动物将返回到的默认姿势。 Current …

边缘计算网关的工作原理及其在工业领域的应用价值-天拓四方

随着物联网技术的快速发展&#xff0c;物联网时代已经悄然来临。在这个时代&#xff0c;数以亿计的设备相互连接&#xff0c;共享数据&#xff0c;共同构建智慧的世界。边缘计算网关通过将计算能力和数据存储推向网络的边缘&#xff0c;实现了对海量数据的实时处理&#xff0c;…

centos云服务器安装cs(cobaltstrike4.0)教程

1、先安装JAVA环境 mkdir download #创建download目录 cd download #进入download目录 mkdir java1.8 #在download目录下再创建java1.8目录 cd java1.8 #进入java1.8目录 wget https://repo.huaweicloud.com/java/jdk/8u201-b09/jdk-8u201-linux-x64.tar.gz #下载jdk压缩包 tar…

WordPress供求插件API文档:获取市场类型

请注意&#xff0c;该文档为&#xff1a; WordPress供求插件&#xff1a;一款专注于同城生活信息发布的插件-CSDN博客文章浏览阅读396次&#xff0c;点赞6次&#xff0c;收藏5次。WordPress供求插件&#xff1a;sliver-urban-life 是一款专注于提供同城生活信息发布与查看的插件…

vue生命周期函数原理解析,vue阻止事件冒泡方法实现

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者简介&#xff1a;景天科技苑 &#x1f3c6;《头衔》&#xff1a;大厂架构师&#xff0c;华为云开发者社区专家博主&#xff0c;…

TransNeXt实战:使用TransNeXt实现图像分类任务(一)

文章目录 摘要安装包安装timm 数据增强Cutout和MixupEMA项目结构计算mean和std生成数据集 摘要 https://arxiv.org/pdf/2311.17132.pdf TransNeXt是一种视觉骨干网络&#xff0c;它集成了聚合注意力作为令牌混合器和卷积GLU作为通道混合器。通过图像分类、目标检测和分割任务…

R在直方图上添加一个更平滑的密度曲线

要在直方图上添加一个更平滑的密度曲线&#xff0c;你可以使用 geom_density() 函数&#xff0c;并调整其 adjust 参数来控制平滑程度。adjust 值越大&#xff0c;曲线越平滑。这里是如何修改你的代码来实现这一点&#xff1a; library(ggplot2) library(ggprism) # for them…

【Hadoop】 Hive:内部表与外部表的创建与查看

感情是偏执的 越爱越是偏执的 不相信我看到的 硬要说裂缝不过 是皱褶 怎么先炽热的却先变冷了 慢热的却停不了还在沸腾着 看时光任性快跑随意就转折 慢冷的人啊 会自我折磨 冲动的人向来听不见挽留 这世界大得让你很难不旅游 浪漫让你温柔 也让你最惹人 泪流 …

安卓性能优化面试题 16-20

16. Android中的图片优化方案?首先我们可以对图片进行二次采样,从本质上减少图片的内存占用。 就是将大图片缩小之后放入到内存中,以实现减小内存的目的其次就是采用三层缓存架构,提高图片的访问速度。 三层缓存架构是内存-文件-网络。 内存是访问速度最快的部分但是分配的…