ElasticSearch7.6 整合Springboot测试API(五)

一、加入ES依赖

特别注意的是:如果是Springboot自带的ES依赖可能跟我们本地的ES版本不一致,记得改为本地版本!

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>7.6.1</version>
</dependency>

要加上阿里的fast-json依赖,因为ES操作的数据都是以JSON为格式的。

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
</dependency>

二、ES配置类

/**
 * 配置ES客户端,注入相应的bean
 * 两步骤: 找要用的对象; 放到spring容器中待用。
 */
@Configuration //xml - bean
public class ElasticSearchClientConfig {

    //注入要操作ES的客户端
    //相当于 spring xml 
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}

三、编写ES的API测试

记得要先启动本地的ES!

@SpringBootTest
class ElasticsearchApiApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 测试索引的创建 Request 相当于 Put test_index
     */
    @Test
    void testCreateIndex() throws IOException {
        // 1. 创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("test_index");
        // 2. 创建客户端执行请求,IndicesClient,得到请求响应
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * 测试索引的获取,只能判断是否存在
     */
    @Test
    void testExistIndex() throws IOException {
        // 1. 获取索引请求
        GetIndexRequest request = new GetIndexRequest("test_index");
        // 2. 客户端执行请求
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     * 测试索引的删除
     */
    @Test
    void testDeleteIndex() throws IOException {
        // 1. 删除索引请求
        DeleteIndexRequest request = new DeleteIndexRequest("test_index");
        // 2. 客户端执行请求 AcknowledgedResponse 是一种返回的响应
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

    /**
     * 测试添加文档
     */
    @Test
    void testAddDocument() throws IOException{
        //创建对象
        User user = new User("linsa",3);
        //创建请求
        IndexRequest request = new IndexRequest("test_index");

        //规则 put /test_index/_doc/1
        request.id("1");
        request.timeout("1s");

        //将我们的数据放入请求,数据格式都要是json
        request.source(JSON.toJSONString(user), XContentType.JSON);

        //使用客户端发送请求,获得响应数据
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse);
        System.out.println(indexResponse.status());
    }

    /**
     * 获得文档的信息
     */
    @Test
    void testGetDocument() throws IOException{
        //获取文档的请求
        GetRequest getRequest = new GetRequest("test_index","1");
        //客户端执行请求
        GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);

        System.out.println(getResponse.getSourceAsString()); //打印文档的内容
        System.out.println(getResponse); //返回全部信息,和命令一样
    }

    /**
     * 更新文档的信息
     */
    @Test
    void testUpdateRequest() throws IOException{
        //更新请求
        UpdateRequest updateRequest = new UpdateRequest("test_index","1");
        updateRequest.timeout("1s");

        //更新对象
        User user = new User("linsa",22);
        //更新对象以json格式放在doc中
        updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);

        //客户端执行请求
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse);
    }

    /**
     * 删除文档记录
     */
    @Test
    void testDeleteRequest() throws IOException{
        //删除请求
        DeleteRequest request = new DeleteRequest("test_index","1");
        request.timeout("1s");

        DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
    }

    /**
     * 批量插入数据
     */
    @Test
    void testBulkRequest() throws IOException{
        //批量请求
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        ArrayList<User> userList = new ArrayList<>();
        userList.add(new User("Tom",12));
        userList.add(new User("Jim",12));
        userList.add(new User("Tom1",12));
        userList.add(new User("Tom2",12));
        userList.add(new User("Tom3",12));
        userList.add(new User("Tom4",12));

        //批量处理请求
        for (int i=0;i<userList.size();i++){
            //要批量添加,更新 或 批量删除,在这里修改对应的请求即可
            bulkRequest.add(
                    new IndexRequest("test_index").id(""+(i+1)).source(
                            JSON.toJSONString(userList.get(i)),XContentType.JSON
                    )
            );
        }

        //客户端执行批量请求
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        //是否失败,返回false表示成功
        System.out.println(bulkResponse.hasFailures());
    }

    /**
     * 特殊的查询:
     *  SearchRequest 搜索请求
     *  SearchSourceBuilder 条件构造
     *  HighlightBuilder 高亮构建
     *  TermQueryBuilder 精准查询
     *  MatchAllQueryBuilder 查询所有匹配
     *  xxxQueryBuilder
     */
    @Test
    void testSearch() throws IOException{
        //搜索请求
        SearchRequest searchRequest = new SearchRequest("test_index");
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //特殊条件
        sourceBuilder.highlighter();
        //查询条件,可以使用QueryBuilders 工具实现
//        QueryBuilders.termQuery() 精确
//        QueryBuilders.matchAllQuery() 匹配所有
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name","Tom");
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(sourceBuilder);

        //客户端执行请求
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //返回命中的数据
        System.out.println(JSON.toJSONString(searchResponse.getHits()));
        //循环输出每条数据
        for (SearchHit documentFields: searchResponse.getHits().getHits()){
            System.out.println(documentFields.getSourceAsMap());
        }
    }
}

你可能感兴趣的:(ElasticSearch)