elasticsearch笔记之java客户端操作

文章目录

一、前言

今天来讲解一下,如何使用java程序操作elasticsearch,实现数据的增删改查,在以往,我们都是通过开启kibana服务来实现es数据的增删改查,但是在真实的开发场景中,这些操作都是需要移植到程序中的,于是就有了今天这篇文章,学习如何使用java程序实现elasticsearch数据的增删改查。

二、使用步骤

1.导入依赖,配置环境

以SpringBoot为基础,创建一个SpringBoot项目。

<!--java版es客户端-->
<dependency>
      <groupId>org.elasticsearch.client</groupId>
      <artifactId>elasticsearch-rest-high-level-client</artifactId>
      <version>7.6.2</version>
</dependency>
<!--特别需要注意的是,填写自己需要使用的es版本,如果没有自己指定,那么就会使用默认的低版本(会报错,这是一个坑)-->
<properties>
    <java.version>1.8</java.version>
    <elasticsearch-version>7.6.2</elasticsearch-version>
</properties>
//我们编写一个测试类,和一个实体类,用于测试elasticsearch中的索引和数据的增删改查的基本操作。
//实体类(使用lombok插件自动生成get/set,有参无参构造,以及toString()方法.)
package com.lhh.es.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
    private int age;
    private String name;
    private char sex;
}
//注入一个elasticsearch的客户端,并把它加入到spring容器当中
@Bean
private static synchronized RestHighLevelClient makeConnection() {
        if (restHighLevelClient == null) {
            restHighLevelClient = new RestHighLevelClient(
                    RestClient.builder(
                            new HttpHost("localhost", 9200, "http")
                    ));
        }
        return restHighLevelClient;
}

elasticsearch笔记之java客户端操作

2.索引测试

elasticsearch笔记之java客户端操作
创建索引

/*
     * 创建一个索引
     * */
    @Test
    void testCreateIndex() throws IOException {
        /*创建了一个索引*/
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("my_java_index1");
        /*运行一个创建索引的命令*/
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        /*打印创建索引之后的信息。*/
        System.out.println(createIndexResponse.index());
    }

elasticsearch笔记之java客户端操作
elasticsearch笔记之java客户端操作
判断索引是否存在

 /*判断索引是否存在*/
    @Test
    void testGetIndex() throws IOException {
        /*定义一个获取索引的操作*/
        GetIndexRequest getIndexRequest = new GetIndexRequest("my_java_index1");
        /*运行获取索引的命令*/
        boolean bool = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        /*打印信息*/
        System.out.println(bool);
    }

elasticsearch笔记之java客户端操作
删除索引

 /*删除索引*/
    @Test
    void testDeleteIndex() throws IOException {
        /*定义一个删除的操作*/
        DeleteIndexRequest my_java_index = new DeleteIndexRequest("my_java_index1");
        /*运行删除命令*/
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(my_java_index, RequestOptions.DEFAULT);
        /*验证是否删除*/
        System.out.println(delete.isAcknowledged());
    }

3.文档测试

创建文档(id需要自己手动设置)

/*
     * 创建文档
     * */
    @Test
    void testCreateDocument() throws IOException {
        IndexRequest my_java_index1 = new IndexRequest("my_java_index1");
        /*设置文档id*/
        my_java_index1.id("1");
        my_java_index1.timeout("2s");

        User user = new User(12, "miracle", '男');

        my_java_index1.source(JSON.toJSONString(user), XContentType.JSON);

        IndexResponse index = restHighLevelClient.index(my_java_index1, RequestOptions.DEFAULT);
        /*查看状态*/
        System.out.println(index.status());
        /*或许文档的信息*/
        System.out.println(index.toString());
    }

elasticsearch笔记之java客户端操作
判断文档是否存在(注意和索引的区别)

/*
     * 判断文档是否存在
     * */
    @Test
    void getDocument() throws IOException {
        GetRequest getRequest = new GetRequest("my_java_index1", "1");
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

elasticsearch笔记之java客户端操作
获取文档的具体信息

/*
     * 获取文档的具体信息
     * */
    @Test
    void getDocumentMessage() throws IOException {
        GetRequest getRequest = new GetRequest("my_java_index1", "1");
        GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        /*获取字段信息*/
        System.out.println(getResponse.getType());
        System.out.println();
        System.out.println(getResponse.getSource());
    }

elasticsearch笔记之java客户端操作
删除文档

 /*
     * 删除文档
     * */
    @Test
    void deleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("my_java_index1", "1");
        DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        /*获取删除文档的信息*/
        System.out.println(deleteResponse.remoteAddress());
        System.out.println(deleteResponse.status());
    }

elasticsearch笔记之java客户端操作
elasticsearch笔记之java客户端操作
更新文档

/*更新文档*/
    @Test
    void testUpdateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("my_java_index1", "2");
        updateRequest.doc(JSON.toJSONString(new User(120,"zhangsan",'女')),XContentType.JSON);
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        /*获取更新之后的信息*/
        System.out.println(updateResponse.status());
    }

elasticsearch笔记之java客户端操作
elasticsearch笔记之java客户端操作
批量插入数据

/*
     * 批量插入
     *
     * */
    @Test
    void testBulkInsert() throws IOException {
        IndexRequest indexRequest = new IndexRequest("my_java_index1");
        List<User> lists = new ArrayList<>(10);
        User user = new User(25, "lisi", '男');
        User user1 = new User(27, "zhaoliu", '女');
        User user2 = new User(20, "tianqi", '男');
        User user3 = new User(15, "haihui", '男');
        lists.add(user1);
        lists.add(user2);
        lists.add(user3);
        lists.add(user);
        BulkRequest bulkRequest = new BulkRequest();

        for (int i = 0; i < lists.size(); i++) {
            bulkRequest.add(indexRequest.id("" + (i + 1)).source(JSON.toJSONString(lists.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures());
    }

批量查询(重要)

/*
    * 批量查询,目前还有点问题尚待解决,会报错。
    * */
    @Test
    void testSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest("my_java_index1");
        /*构建搜索的条件*/
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhangsan");
        searchSourceBuilder.query(termQueryBuilder);

        searchRequest.source(searchSourceBuilder);

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

    }

总结

以上介绍了如何增删改查索引 文档还讲解了如何实现批量插入,以及一些复杂的查询。

上一篇:Leetcode167. 两数之和 II - 输入有序数组


下一篇:Leetcodet题目解析-1 c++版