SpringBoot集成ES

ES的Java API

  1. Transport Client:TransportClient不推荐使用,而推荐使用Java High Level REST Client,并将在Elasticsearch 8.0中删除。
  2. JAVA REST Client
    • Java Low Level REST Client:低级别的REST客户端,通过http与集群交互,用户需自己编组请求JSON串,及解析响应JSON串。兼容所有ES版本
    • Java High Level REST Client:高级别的REST客户端,基于低级别的REST客户端,增加了编组请求JSON串、解析响应JSON串等相关api。使用的版本需要保持和ES服务端的版本一致,否则会有版本问题。同时要求JDK版本最少为1.8

基于SpringBoot和Java High Level REST Client实现CRUD

添加依赖

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
        <!-- es版本需要和安装es版本一致-->
        <es.version>7.12.1</es.version>
        <fastjson.version>1.2.70</fastjson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!--es -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

添加配置类

@Configuration
public class ElasticSearchClientConfig {
    // 相较xml<bean id="方法名" class="返回值">
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.232.128", 9200, "http")));
    }
}

新增实体类

//此处需要继承Serializable,不然在实体类转json会失败
@Data
@AllArgsConstructor
public class User implements Serializable {
    private  String name;
    private int age;
}

索引的CURD

package com.example.demo.test;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

/**
 *
 * @version 1.0
 * @ClassName IndexTest
 * @Description  对索引的CURD   client.indices():获取关于indexClient,来得到对index操作的权力
 * @date 2021/5/27 14:33
 */
@SpringBootTest
public class IndexTest {
    @Autowired
    @Qualifier("restHighLevelClient")  //指定注入的bean
    private RestHighLevelClient restHighLevelClient;


    /**
    * 创建索引,重复创建会抛出相关异常
    * */
    @Test
    public void contextLoadTest() throws IOException {
        CreateIndexRequest my_index = new CreateIndexRequest("my_index");
        System.out.println(restHighLevelClient);
        CreateIndexResponse indexResponse = restHighLevelClient.indices().create(my_index, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());
    }

    /**
     * 查询索引是否存在
     */
    @Test
    public  void existRequest() throws IOException {
        GetIndexRequest my_index = new GetIndexRequest("my_index");
        System.out.println(my_index.toString());
        boolean exists = restHighLevelClient.indices().exists(my_index, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     *
     * 删除索引,索引不存在会抛出相关异常
    * */
    @Test
    public void deleteRequest() throws IOException {
        DeleteIndexRequest my_index = new DeleteIndexRequest("my_index");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(my_index, RequestOptions.DEFAULT);
        System.out.println(delete.toString());
    }
}

DOC的CRUD

package com.example.demo.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.pojo.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

/**
 *
 * @version 1.0
 * @ClassName DocTest
 * @Description 对文档的CRUD
 * @date 2021/5/27 14:52
 */
@SpringBootTest
public class DocTest {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    /**
     * 添加doc,当指定id的数据存在时,则会变成全量update,却字段会导致数据丢失
     */
    @Test
    public  void addDocTest() throws IOException {
        //创建请求连接
        IndexRequest request = new IndexRequest("my_index");
        //创建要添加的信息
        User user = new User("孙悟空", 700);
        //通过客户端对基本信息进行添加
        //自定义id
        request.id("1");
        //请求超时时间
        request.timeout("10s");
        //将请求的数据放到request中,并指定消息类型为json
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //通过客户端传递请求
        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(index.toString());
        System.out.println(index.status());
    }


    /**
     * 修改doc,(上面的创建其实是可以智能的在有数据的情况下是更新数据,但是是全量的更新,缺字段会导致数据丢失)
     */
    @Test
    public void updateDoc() throws IOException {
        //修改指定id的doc数据,此时如果id不存在会抛出未找到的异常
        UpdateRequest updateRequest = new UpdateRequest("my_index", "1");
        updateRequest.timeout("5s");
        User user = new User("猪八戒", 300);
         updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
         //获取修改之后的结果
        updateRequest.fetchSource(true);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.toString());
        System.out.println(update.getIndex());
        System.out.println(update.getGetResult());
        System.out.println(update.status());

    }

    /**
     * 删除doc 
     *
     */
    @Test
    public  void deleteDoc() throws IOException {
        //创建删除请求,指定索引和删除id
        DeleteRequest deleteRequest = new DeleteRequest("my_index", "1");
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.status());
        System.out.println(delete.toString());

    }
}

posted @ 2021-06-08 16:03  知白守黑,和光同尘  阅读(1007)  评论(0编辑  收藏  举报