SpringBoot集成Elasticsearch8.x(6)|(新版本Java API Client使用)

SpringBoot集成Elasticsearch8.x(6)|(新版本Java API Client使用)


章节
章节
第一章链接: SpringBoot集成Elasticsearch7.x(1)|(增删改查功能实现)
第二章链接: SpringBoot集成Elasticsearch7.x(2)|(复杂查询)
第三章链接: SpringBoot集成Elasticsearch7.x(3)|(aggregations之指标聚合查询)
第四章链接: SpringBoot集成Elasticsearch7.x(4)|(aggregations之分桶聚合查询)
第五章链接: SpringBoot集成Elasticsearch7.x(5)|(term、match、match_phrase区别)
第六章链接: SpringBoot集成Elasticsearch8.x(6)|(新版本Java API Client使用)
第七章链接: SpringBoot集成Elasticsearch8.x(7)|(新版本Java API Client使用完整示例)

前言

ElasticSearch在7.17版本之前使用的java客户端是Java REST Client,但是从7.17版本开始,官方将Java REST Client标记为弃用(deprecated),推荐使用新版Java Client。 本文介绍新版ElasticSearch Java Client的基本用法

一、ElasticSearch客户端版本介绍

1、JAVA REST client ES提供了两个REST客户端版本(7.17版本后使用)

Java Low Level REST Client :用于Elasticsearch的官方低级客户端。它允许通过http与Elasticsearch集群通信。将请求编排和响应反编排留给用户自己处理。它兼容所有的Elasticsearch版本。
ava High Level REST Client :用于Elasticsearch的官方高级客户端。它是基于低级客户端的,它提供很多API,并负责请求的编排与响应的反编排。( PS:就好比是,一个是传自己拼接好的字符串,并且自己解析返回的结果;而另一个是传对象,返回的结果也已经封装好了,直接是对象,更加规范了参数的名称以及格式,更加面对对象一点)

2、TransportClient client

使用Transport 接口进行通信,能够使用ES集群中的一些特性,性能最好。JAR包版本需与ES集群版本一致,ES集群升级,客户端也跟着升级到相同版本

3、ElasticSearch Java Client(8.x版本推荐使用)

Java API Client包含三部分:java客户端对应的类是ElasticsearchClient,一个JSON object mapper用于数据的序列化和反序列化,底层Transport通信,并且还提供了同步和异步调用,流式和函数式调用,与Jackson无缝集成,封装了连接池、重试、json序列化等通用能力

二、依赖引入及配置

1.elasticsearch客户端的依赖以及jackson依赖

jackson依赖通常在springboot项目中有,可以不需要,elasticsearch8.x官方是对剑在springbott3.x上使用,至于低版本的是否可行需要验证。

  <dependency>
  <groupId>co.elastic.clients</groupId>
  <artifactId>elasticsearch-java</artifactId>
  <version>8.5.3</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.12.3</version>
</dependency>

2.客户端和es服务连接配置

这里我们初始化了三种客户端
1、低级客户端
2、通信 Transport,并利用 JacksonJsonpMapper 做数据的解析。
3、阻塞的 Java 客户端

RestClient restClient = RestClient.builder(
    new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
    restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);

三、索引操作

1.判断索引是否存在

实现代码如下

   
    /**
     * 判断索引是否存在
     *
     * @param indexName
     * @return
     * @throws IOException
     */
    public boolean hasIndex(String indexName) throws IOException {
    
    
        BooleanResponse exists = client.indices().exists(d -> d.index(indexName));
        return exists.value();
    }

2.删除索引

实现代码如下

   
      /**
     * 删除索引
     *
     * @param indexName
     * @throws IOException
     */
    public boolean deleteIndex(String indexName) throws IOException {
    
    
        DeleteIndexResponse response = client.indices().delete(d -> d.index(indexName));
        return true;
    }

3.创建索引

实现代码如下

     /**
     * 创建索引,不允许外部直接调用
     *
     * @param indexName
     * @param mapping
     * @throws IOException
     */
    private boolean createIndex(String indexName, Map<String, Property> mapping) throws IOException {
    
    
        CreateIndexResponse createIndexResponse = client.indices().create(c -> {
    
    
            c.index(indexName).mappings(mappings -> mappings.properties(mapping));
            return c;
        });
        return createIndexResponse.acknowledged();
    }
    

构建mapping

    public Map<String, Property> buildMappingV2( Map<String, String> propertyKeys) {
    
    
        Map<String, Property> documentMap = new HashMap<>();
        for (Map.Entry<String, String> propertyKey : propertyKeys.entrySet()) {
    
    
            String type = getIndxPropType(propertyKey.getValue());
            String key = propertyKey.getKey();
            log.info("属性:{}类型:{}", key, type);
            if (type.equals("text")) {
    
    
                documentMap.put(key, Property.of(property ->
                                property.keyword(KeywordProperty.of(p ->
                                                p.index(true)
                                        )
                                )
                        )
                );
            } else if (type.equals("date")) {
    
    
                documentMap.put(key, Property.of(property ->
                                property.date(DateProperty.of(p ->
                                                p.index(true).format("yyyy-MM-dd HH:mm:ss.SSS")
                                        )
                                )
                        )
                );
            } else if (type.equals("long")) {
    
    
                documentMap.put(key, Property.of(property ->
                                property.long_(LongNumberProperty.of(p ->
                                                p.index(true)
                                        )
                                )
                        )
                );
            } else if (type.equals("integer")) {
    
    
                documentMap.put(key, Property.of(property ->
                                property.integer(
                                        IntegerNumberProperty.of(p ->
                                                p.index(false)
                                        )
                                )
                        )
                );
            } else {
    
    
                documentMap.put(key, Property.of(property ->
                                property.object(
                                        ObjectProperty.of(p ->
                                                p.enabled(true)
                                        )
                                )
                        )
                );
            }
        }
        return documentMap;
    }

4.重新创建索引

实现代码如下

 /**
     * 重新创建索引,如果已存在先删除
     *
     * @param indexName
     * @param mapping
     */
    public void reCreateIndex(String indexName, Map<String, Property> mapping) {
    
    
        try {
    
    
            if (this.hasIndex(indexName)) {
    
    
                this.deleteIndex(indexName);
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
            throw new WrapperException(RetCode.NOT_AVAILABLE, "删除索引失败");
        }

        try {
    
    
            this.createIndex(indexName, mapping);
        } catch (IOException e) {
    
    
            e.printStackTrace();
            throw new WrapperException(RetCode.NOT_AVAILABLE, "重新创建索引失败");
        }
    }
    
# 总结

以上就是SpringBoot集成Elasticsearch数据库内容,在验证过程中遇到很多问题,输出的文档都是经过验证可执行的,后续会慢慢更新文章,尽量覆盖全面,如果大家在使用过程中遇到问题欢迎留言。



猜你喜欢

转载自blog.csdn.net/Oaklkm/article/details/128956998