Elasticsearch rest-high-level-client 基本操作
Elasticsearch rest-high-level-client 基本操作
本篇主要讲解一下 rest-high-level-client 去操作 Elasticsearch , 虽然这个客户端在后续版本中会慢慢淘汰,但是目前大部分公司中使用Elasticsearch 版本都是6.x 所以这个客户端还是有一定的了解

前置准备
- 准备一个SpringBoot环境 2.2.11 版本
- 准备一个Elasticsearch 环境 我这里是8.x版本
- 引入依赖 elasticsearch-rest-high-level-client 7.4.2
1.配置依赖
注意: 我使用的是 springboot 2.2.11 版本 , 它内部的 elasticsearch 和 elasticsearch-rest-client 都是 6.8.13 需要注意
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 引入 elasticsearch 7.4.2 -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.2</version>
<exclusions>
<exclusion>
<artifactId>log4j-api</artifactId>
<groupId>org.apache.logging.log4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 排除 elasticsearch-rest-client , 也可不排除 为了把maven冲突解决 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</exclusion>
<exclusion>
<artifactId>elasticsearch</artifactId>
<groupId>org.elasticsearch</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 不引入会导致可能 使用 springboot的 elasticsearch-rest-client 6.8.13 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.4.2</version>
</dependency>
<!-- elasticsearch 依赖 2.x 的 log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
<!-- 排除掉 log4j-api 因为springbootstarter 中引入了loging模块 -->
<exclusions>
<exclusion>
<artifactId>log4j-api</artifactId>
<groupId>org.apache.logging.log4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- junit 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2.构建 RestHighLevelClient
highlevelclient 是 高级客户端 需要通过它去操作 Elasticsearch , 它底层也是要依赖 rest-client 低级客户端
@Slf4j
public class TestEsClient {
private RestHighLevelClient client = null;
private ObjectMapper objectMapper = new ObjectMapper();
//构建 RestHighLevelClient
@Before
public void prepare() {
// 创建Client连接对象
String[] ips = {"172.16.225.111:9200"};
HttpHost[] httpHosts = new HttpHost[ips.length];
for (int i = 0; i < ips.length; i++) {
httpHosts[i] = HttpHost.create(ips[i]);
}
RestClientBuilder builder = RestClient.builder(httpHosts);
client = new RestHighLevelClient(builder);
}
}
3.创建索引 client.indices().create
创建索引 需要使用 CreateIndexRequest 对象 , 操作 索引基本上是 client.indices().xxx
构建 CreateIndexRequest 对象
@Test
public void test1() {
CreateIndexRequest request = new CreateIndexRequest("blog1");
try {
CreateIndexResponse createIndexResponse =
client.indices().create(request, RequestOptions.DEFAULT);
boolean acknowledged = createIndexResponse.isAcknowledged();
log.info("[create index blog :{}]", acknowledged);
} catch (IOException e) {
e.printStackTrace();
}
}
4.删除索引 client.indices().delete
构建 DeleteIndexRequest 对象
@Test
public void testDeleteIndex(){
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("blog1");
try {
AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
log.info("[delete index response: {}", response.isAcknowledged());
} catch (IOException e) {
e.printStackTrace();
}
}
4.查询索引 client.indices().get
构建 GetIndexRequest 对象
@Test
public void testSearchIndex() {
GetIndexRequest request = new GetIndexRequest("blog1");
try {
GetIndexResponse getIndexResponse =
client.indices().get(request, RequestOptions.DEFAULT);
Map<String, List<AliasMetaData>> aliases = getIndexResponse.getAliases();
Map<String, MappingMetaData> mappings = getIndexResponse.getMappings();
Map<String, Settings> settings = getIndexResponse.getSettings();
log.info("[aliases: {}]", aliases);
log.info("[mappings: {}]", mappings);
log.info("[settings: {}", settings);
} catch (IOException e) {
e.printStackTrace();
}
}

可以根据 response 获取 aliases , mappings , settings 等等 和 Kibana 中返回的一样

5.插入文档 client.index
插入文档 需要使用 IndexRequest 对象 , 注意 不是 InsertRequest , 不知道为什么不这样定义 感觉会更加好理解
request.source(blogInfoJsonStr, XContentType.JSON);
@Test
public void insertDoc() {
IndexRequest request = new IndexRequest();
request.index("blog1").id("1");
BlogInfo blogInfo =
new BlogInfo()
.setBlogName("Elasticsearch 入门第一章")
.setBlogType("Elasticsearch")
.setBlogDesc("本篇主要介绍了Elasticsearch 的基本client操作");
try {
//提供java 对象的 json str
String blogInfoJsonStr = objectMapper.writeValueAsString(blogInfo);
request.source(blogInfoJsonStr, XContentType.JSON);
// 这里会抛错 原因是 我的 Elasticsearch 版本8.x 而 使用的 restHighLevel 已经解析不了,因为新的es已经不推荐使用
// restHighLevel,而使用 Elasticsearch Java API Client
IndexResponse index = client.index(request, RequestOptions.DEFAULT);
log.info("[Result insert doc :{} ]", index);
} catch (IOException e) {
}
}
6.查询文档 client.get
注意 getResponse.getSourceAsString() 返回文档数据
@Test
public void testSelectDoc() {
GetRequest getRequest = new GetRequest();
getRequest.index("blog1").id("1");
try {
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
BlogInfo blogInfo =
objectMapper.readValue(getResponse.getSourceAsString(), BlogInfo.class);
log.info("[get doc :{}] ", blogInfo);
} catch (IOException e) {
e.printStackTrace();
}
}

7.删除文档 client.delete
注意 删除文档 的 response 也解析不了 Elasticsearch 8.x 版本
@Test
public void testDeleteDoc() {
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.index("blog1").id("1");
try {
// 这里也会抛错 和上面的一样
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
log.info("[delete response:{} ]", deleteResponse);
} catch (IOException e) {
}
}
总结
本篇主要介绍了 java 操作Elasticsearch 的客户端 rest-high-level-client 的基本使用 , 如果你是使用springboot 需要注意jar 冲突问题, 后续操作 Elasticsearch 客户端 逐渐变成 Elasticsearch Java API Client , 不过目前大部分还是使用 rest-high-level-client
欢迎大家访问 个人博客 Johnny小屋
欢迎关注个人公众号

Elasticsearch rest-high-level-client 基本操作的更多相关文章
- springboot整合elasticsearch(基于es7.2和官方high level client)
前言 最近写的一个个人项目(传送门:全终端云书签)中需要用到全文检索功能,目前 mysql,es 都可以做全文检索,mysql 胜在配置方便很快就能搞定上线(参考这里),不考虑上手难度,es 在全文检 ...
- elasticsearch java 客户端之Client简介
elasticsearch通过构造一个client对外提供了一套丰富的java调用接口.总体来说client分为两类cluster信息方面的client及数据(index)方面的client.这两个大 ...
- ElasticSearch的javaAPI之Client
翻译的原文:http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/client.html#node-c ...
- Elasticsearch Java Low Level REST Client(嗅探器)
https://segmentfault.com/a/1190000016828977?utm_source=tag-newest#articleHeader0 嗅探器 允许从正在运行的Elastic ...
- springboot 配置elasticsearch Java High Rest Client
前提声明 在新版本的spring boot中逐渐放弃了对Spring Data Elasticsearch的支持,所以不推荐使用,使用ES官方推出的Java High Rest Client. 引入依 ...
- Elasticsearch【JAVA REST Client】客户端操作
ES系统作为集群,环境搭建非常方便简单. 现在在我们的应用中,如何对这个集群进行操作呢? 我们利用ES系统,通常都是下面的架构: 在这里,客户端的请求通过LB进行负载均衡,因为操作任何一个ES的实例, ...
- ElasticSearch的基本认识和基本操作
1.1. ElasticSearch(简称ES) ES即为了解决原生Lucene使用的不足,优化Lucene的调用方式,并实现了高可用的分布式集群的搜索方案,其第一个版本于2010年2月出现在Git ...
- JAVA Rest High Level Client如何取聚合后得数据
对于刚刚学习es的童鞋来说,很容易不清楚怎么获取客户端对es文档的聚合结果,下面就演示一下模仿DSL写聚合,然后获取到聚合对结果. 一, 对于下面这个简单的聚合,目的是对于文档全文匹配,聚合颜色字段. ...
- elasticsearch Java High Level REST 相关操作封装
pox.xml文件添加以下内容 <dependency> <groupId>org.elasticsearch.client</groupId> <artif ...
- 【ELK】【ElasticSearch】3.es入门基本操作
docker安装elasticSearch步骤 ================================================================== 本篇参考: htt ...
随机推荐
- 【AGC】引导用户购买提升用户留存率
借助AGC的云数据库.云托管.应用内消息.App Linking等服务,您可以给不同价值用户设置不同的优惠套餐活动,引导用户持续购买,增强用户黏性.判断用户价值,发送营销短信,引导用户参与营销活动,提 ...
- Spring源码 21 Bean生命周期
参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...
- 大家都能看得懂的源码 - ahooks useSet 和 useMap
本文是深入浅出 ahooks 源码系列文章的第十篇,该系列已整理成文档-地址.觉得还不错,给个 star 支持一下哈,Thanks. 今天我们来聊聊 ahooks 中对 Map 和 Set 类型进行状 ...
- Python小游戏——外星人入侵(保姆级教程)第一章 05重构模块game_functions
系列文章目录 第一章:武装飞船 05:重构:模块game_functions 一.重构 在大型项目中,经常需要在添加新代码前重构既有代码.重构旨在简化既有代码的结构,使其更容易扩展.在本节中,我们将创 ...
- 你必须学UML之理论篇
1.前言 对于当前社会背景下从事软件开发的工作者而言,"写代码"实际上并不是唯一的工作.特别在一些中小型的企业当中,这些企业往往对于开发者的要求,不单单停留在写代码完成相应功能上, ...
- 系统CPU飙高,怎么排查?
cpu是整个电脑的核心计算资源,对于一个应用进程来说,cpu的最小执行单元是线程. 导致cpu飙高的原因有几个方面: cpu上下文切换过多,对于cpu来说,同一时刻下每个cpu核心只能运行一个线程,如 ...
- [CF1537E] Erase and Extend (字符串)
题面 给一个长度为 n \tt n n 的字符串,你可以进行无限次以下两种操作之一: 删去末尾的字符(此时要保证删去后字符串非空). 把当前整个字符串复制一份,接到自己的后面. 输出最终通过操作能达到 ...
- Seatunnel超高性能分布式数据集成平台使用体会
@ 目录 概述 定义 使用场景 特点 工作流程 连接器 转换 为何选择SeaTunnel 安装 下载 配置文件 部署模式 入门示例 启动脚本 配置文件使用参数示例 Kafka进Kafka出的ETL示例 ...
- dotnet 设计规范 · 抽象类
X 不要定义 public 或 protected internal 访问的构造函数.默认 C# 语言不提供抽象类的公开构造函数方法. 如果一个构造函数定义为公开,只有在开发者需要创建这个类的实例的时 ...
- omc.
OMC 099(4b) D 因为 \((abc)^{\dfrac 13} \le \dfrac{a+b+c}3\)(基本不等式),将 \(a = xy, b = yz, c = xz\) 代入得到 \ ...