首页 > 其他分享 >Elasticsearch rest-high-level-client 基本操作

Elasticsearch rest-high-level-client 基本操作

时间:2022-10-25 16:25:37浏览次数:82  
标签:level rest client Elasticsearch elasticsearch org 基本操作 new

Elasticsearch rest-high-level-client 基本操作

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

image-20221025135725969

前置准备

  • 准备一个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();
    }
}

image-20221025110635194

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

image-20221025110052958

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();
    }
}

image-20221025110707411

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小屋
欢迎关注个人公众号

欢迎关注个人公众号

标签:level,rest,client,Elasticsearch,elasticsearch,org,基本操作,new
From: https://www.cnblogs.com/askajohnny/p/16825264.html

相关文章

  • 实验7:基于REST API的SDN北向应用实践
    实验7:基于RESTAPI的SDN北向应用实践(一)基本要求1.编写Python程序,调用OpenDaylight的北向接口实现以下功能(1)利用Mininet平台搭建下图所示网络拓扑,并连接OpenDaylight;(2)......
  • 实验7:基于REST API的SDN北向应用实践
    实验7:基于RESTAPI的SDN北向应用实践(一)基本要求1、编写Python程序,调用OpenDaylight的北向接口实现以下功能:(1)利用Mininet平台搭建下图所示网络拓扑,并连接OpenDayligh......
  • Nearest Excluded Points ( 转化思想 +多源BFS )
     思路:思路暴力枚举每一个点,暴力做时间会超观察发现:每一个所找的空白点,一定是紧紧挨着红色的点, 于是把这些空白点入队,然后利用bfs,即可搞出来空间用ma......
  • 实验7:基于REST API的SDN北向应用实践
    一、基本要求:①、编写Python程序,调用OpenDaylight的北向接口实现以下功能:1、删除s1上的流表数据代码及其截图:#!/usr/bin/pythonimportrequestsfromrequests.authim......
  • 实验7:基于REST API的SDN北向应用实践
    (一)基本要求1.编写Python程序,调用OpenDaylight的北向接口实现以下功能。    (1)利用Mininet平台搭建下图所示网络拓扑,并连接OpenDaylight    (2)下发指令删除s1上......
  • 实验7:基于REST API的SDN北向应用实践
    实验7:基于RESTAPI的SDN北向应用实践(一)基本要求1、编写Python程序,调用OpenDaylight的北向接口实现以下功能(1)利用Mininet平台搭建下图所示网络拓扑,并连接OpenDaylight;......
  • 实验7:基于REST API的SDN北向应用实践
    基础要求1.编写Python程序,调用OpenDaylight的北向接口实现以下功能利用Mininet平台搭建下图所示网络拓扑,并连接OpenDaylight;下发指令删除s1上的流表数据#delet......
  • 【数据结构-队列】队列的基本操作
    目录1顺序表实现队列(循环队列)1.1定义1.2初始化1.3判队空1.4判队满1.5出队1.6入队1.7队长2单向链表实现队列2.1定义2.2初始化2.3判队空2.4判队满2.5出队2.6......
  • 实验7:基于REST API的SDN北向应用实践
    (一)基本要求1.编写Python程序,调用OpenDaylight的北向接口实现以下功能调用OpenDaylight的北向接口获取拓扑信息importrequestsasrqfromrequests.authimportHTTP......
  • LEVEL UP!想成为关卡策划的小白.1
    “关卡”是什么?-->·(level=关卡)游戏行为发生的环境或地理位置。-->·(level=关卡)在开发者当中使用的术语,用来描述由基于特定游戏体验的物理空间分割而成的单元。-->·(lev......