Java操作Elasticsearch rest-high-level-client 的基本使用

 更新时间:2022年10月25日 16:49:23   作者:AskaJohnny  
这篇文章主要介绍了Java操作Elasticsearch rest-high-level-client 的基本使用,本篇主要讲解一下 rest-high-level-client 去操作 Elasticsearch的方法,结合实例代码给大家详细讲解,需要的朋友可以参考下

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

}

5.查询索引 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 中返回的一样

6.插入文档 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) {
    }

7.查询文档 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();
    }
}

8.删除文档 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

到此这篇关于Java操作Elasticsearch rest-high-level-client 的基本使用的文章就介绍到这了,更多相关Elasticsearch rest-high-level-client内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • GSON实现Java对象与JSON格式对象相互转换的完全教程

    GSON实现Java对象与JSON格式对象相互转换的完全教程

    GSON是Google编写并在在GitHub上开源的Java序列化与反序列化JSON的类库,今天我们就来总结一下使用GSON实现Java对象与JSON格式对象相互转换的完全教程
    2016-06-06
  • 剑指Offer之Java算法习题精讲二叉树与链表

    剑指Offer之Java算法习题精讲二叉树与链表

    跟着思路走,之后从简单题入手,反复去看,做过之后可能会忘记,之后再做一次,记不住就反复做,反复寻求思路和规律,慢慢积累就会发现质的变化
    2022-03-03
  • MyBatis框架简介及入门案例详解

    MyBatis框架简介及入门案例详解

    MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注SQL本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码,本文将作为最终篇为大家介绍MyBatis的使用
    2022-08-08
  • SpringBoot如何配置数据库主从shardingsphere

    SpringBoot如何配置数据库主从shardingsphere

    这篇文章主要介绍了SpringBoot如何配置数据库主从shardingsphere问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04
  • 基于Java事件监听编写一个中秋猜灯谜小游戏

    基于Java事件监听编写一个中秋猜灯谜小游戏

    众所周知,JavaSwing是Java中关于窗口开发的一个工具包,可以开发一些窗口程序,然后由于工具包的一些限制,导致Java在窗口开发商并没有太多优势,不过,在JavaSwing中关于事件的监听机制是我们需要重点掌握的内容,本文将基于Java事件监听编写一个中秋猜灯谜小游戏
    2023-09-09
  • 排查Java应用内存泄漏问题的步骤

    排查Java应用内存泄漏问题的步骤

    这篇文章主要介绍了排查Java应用内存泄漏问题的步骤,帮助大家更好的理解和学习Java,感兴趣的朋友可以了解下
    2020-11-11
  • Java常用正则表达式验证类完整实例【邮箱、URL、IP、电话、身份证等】

    Java常用正则表达式验证类完整实例【邮箱、URL、IP、电话、身份证等】

    这篇文章主要介绍了Java常用正则表达式验证类,结合完整实例形式分析了Java针对邮箱、网址URL、IP地址、电话、身份证等正则验证相关操作技巧,需要的朋友可以参考下
    2018-12-12
  • SpringBoot中使用MyBatis-Plus详细步骤

    SpringBoot中使用MyBatis-Plus详细步骤

    MyBatis-Plus是MyBatis的增强工具,简化了MyBatis的使用,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2025-01-01
  • Java使用Geodesy进行地理计算的技术指南

    Java使用Geodesy进行地理计算的技术指南

    在地理信息系统 (GIS) 和导航应用中,精确的地理计算是基础,Geodesy 是一个流行的 Java 库,用于处理地理位置、距离、方向等相关计算,本博客将介绍 Geodesy 的核心功能,并提供详细的实践样例,帮助开发者快速上手,需要的朋友可以参考下
    2025-02-02
  • 如何使用Java redis实现发送手机验证码功能

    如何使用Java redis实现发送手机验证码功能

    这篇文章主要介绍了如何使用Java redis实现发送手机验证码功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05

最新评论