当前位置:   article > 正文

Java 操作RestHighLevelClient基本使用

resthighlevelclient

在使用 RestHighLevelClient的过程中发现,它已经标记为过时了。

在 Elasticsearch7.15版本之后,Elasticsearch官方将它的高级客户端 RestHighLevelClient标记为弃用状态。
同时推出了全新的 Java API客户端 Elasticsearch Java API Client,该客户端也将在 Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。

由于项目中使用的是低版本的ES。所有有必要记录一下它的基本使用。

参考官方AP文档:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.17/java-rest-high-supported-apis.html

一、将连接信息封装成工具类

引入依赖:

    <!--与ES安装版本保持一致-->
    <dependency>
      <groupId>org.elasticsearch.client</groupId>
      <artifactId>elasticsearch-rest-high-level-client</artifactId>
      <version>7.17.4</version>
    </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

新建工具类,简单封装一下。

public class ESUtil {
    private static RestHighLevelClient restHighLevelClient;

    static {
        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost("192.168.xxx.xxx", 9200, "http"));
        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        System.out.println("==========Connect to Elasticsearch successfully================");
    }

    public static RestHighLevelClient getRestHighLevelClient() {
        return restHighLevelClient;
    }

    @Test
    public void test(){
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
        System.out.println(restHighLevelClient);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

二、索引操作

1、创建索引

1.1 默认创建索引

    // 创建索引(PUT /索引名称)
    @Test
    public void testCreateIndex() throws IOException {
        // 1、获取客户端
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
        // 2、创建索引请求
        CreateIndexRequest indexRequest = new CreateIndexRequest("db_index1");
        // 3、客户端执行请求 IndicesClient,请求后获得响应
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.index());
        System.out.println(createIndexResponse.isAcknowledged());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

查看索引信息:

{
  "db_index1" : {
    "aliases" : { },
    "mappings" : {
      "properties" : {
        "age" : {
          "type" : "long"
        },
        "createTime" : {
          "type" : "long"
        },
        "email" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "height" : {
          "type" : "float"
        },
        "id" : {
          "type" : "long"
        },
        "updateTime" : {
          "type" : "long"
        },
        "userName" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "version" : {
          "type" : "long"
        }
      }
    },
    "settings" : {
      "index" : {
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "1",
        "provided_name" : "db_index1",
        "creation_date" : "1661680036350",
        "number_of_replicas" : "1",
        "uuid" : "fwgaTuOBRkKr092qLRTHsw",
        "version" : {
          "created" : "7170499"
        }
      }
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

1.2 指定参数创建索引

    /**
     * 创建索引,使用ik分词器
     * @throws IOException
     */
    @Test
    public void createIndex() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
        CreateIndexRequest request = new CreateIndexRequest("db_index2");
        // 设置setting
        request.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2)
                .put("index.analysis.analyzer.default.type", "ik_max_word") //指定 ik分词器作为默认分词器
        );

        // 设置mapping
        String mapping = "{\n" +
                "      \"properties\" : {\n" +
                "        \"age\" : {\n" +
                "          \"type\" : \"long\"\n" +
                "        },\n" +
                "        \"createTime\" : {\n" +
                "          \"type\" : \"long\"\n" +
                "        },\n" +
                "        \"email\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"fields\" : {\n" +
                "            \"keyword\" : {\n" +
                "              \"type\" : \"keyword\",\n" +
                "              \"ignore_above\" : 256\n" +
                "            }\n" +
                "          }\n" +
                "        },\n" +
                "        \"height\" : {\n" +
                "          \"type\" : \"float\"\n" +
                "        },\n" +
                "        \"id\" : {\n" +
                "          \"type\" : \"long\"\n" +
                "        },\n" +
                "        \"updateTime\" : {\n" +
                "          \"type\" : \"long\"\n" +
                "        },\n" +
                "        \"userName\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"fields\" : {\n" +
                "            \"keyword\" : {\n" +
                "              \"type\" : \"keyword\",\n" +
                "              \"ignore_above\" : 256\n" +
                "            }\n" +
                "          }\n" +
                "        },\n" +
                "        \"version\" : {\n" +
                "          \"type\" : \"long\"\n" +
                "        }\n" +
                "      }\n" +
                "    }";
        /**
         * 由于是过时的方法,则 mapping方法需要加_doc。
         */
        request.mapping("_doc", mapping, XContentType.JSON);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.index());
        System.out.println(createIndexResponse.isAcknowledged());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

查看索引信息:

{
  "db_index2" : {
    "aliases" : { },
    "mappings" : {
      "properties" : {
        "age" : {
          "type" : "long"
        },
        "createTime" : {
          "type" : "long"
        },
        "email" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "height" : {
          "type" : "float"
        },
        "id" : {
          "type" : "long"
        },
        "updateTime" : {
          "type" : "long"
        },
        "userName" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "version" : {
          "type" : "long"
        }
      }
    },
    "settings" : {
      "index" : {
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "3",
        "provided_name" : "db_index2",
        "creation_date" : "1661692389533",
        "analysis" : {
          "analyzer" : {
            "default" : {
              "type" : "ik_max_word"
            }
          }
        },
        "number_of_replicas" : "2",
        "uuid" : "3o0lJVxYT5S7ycg36nrP5A",
        "version" : {
          "created" : "7170499"
        }
      }
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71

2、查询索引

    // 查询索引(GET /索引名称/参数)
    @Test
    public void testGetIndex() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
        GetIndexRequest indexRequest = new GetIndexRequest("db_index1");
        //获取
        GetIndexResponse indexResponse = restHighLevelClient.indices().get(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.getAliases());
        System.out.println(indexResponse.getMappings());
        System.out.println(indexResponse.getSettings());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3、判断索引是否存在

    // 判断索引是否存在
    @Test
    public void testExistIndex() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
        GetIndexRequest indexRequest = new GetIndexRequest("db_index1");
        //存在
        boolean exists = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4、删除索引

    // 删除索引(DELETE /索引名称)
    @Test
    public void testDeleteIndex() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
        DeleteIndexRequest request = new DeleteIndexRequest("db_index2");
        // 删除
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

三、文档操作

@Data
@ToString
public class UserVO {

    private Long id;

    private String userName;

    private Integer age;

    private Double height;

    private String email;

    private Date createTime;

    private Date updateTime;

    private Integer enabled;

    private Integer version;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

1、添加文档

    /**
     * 添加文档(POST /索引名称/[_doc | _create ]/id)。如果 id已存在,则会全量修改。
     *
     * @throws IOException
     */
    @Test
    public void testAddDocument() throws IOException {
        // 1、获取客户端
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();

        // 2、构建文档数据
        UserVO userVO = new UserVO();
        userVO.setId(1L);
        userVO.setUserName("赵云2");
        userVO.setAge(18);
        userVO.setCreateTime(new Date());
        userVO.setUpdateTime(new Date());
        userVO.setEmail("ss.com");
        userVO.setVersion(1);
        userVO.setHeight(12D);
        // 创建请求
        IndexRequest indexRequest = new IndexRequest("db_index1"); //索引不存在时,会自动创建
        indexRequest.id(userVO.getId().toString());
        indexRequest.timeout(TimeValue.timeValueSeconds(1));
        indexRequest.timeout("1s");
        // 3、将文档数据放入请求 json
        indexRequest.source(JSON.toJSONString(userVO), XContentType.JSON);
        // 4、客户端发送请求 , 获取响应的结果
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString()); //
        System.out.println(indexResponse.status()); // 对应命令返回的状态CREATED/OK
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

2、获取文档

    // 获得文档记录(get //索引名称/doc/id)
    @Test
    public void testGetDocument() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();

        GetRequest getRequest = new GetRequest("db_index1", "1");
        //获取
        GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(getResponse.getSourceAsString()); // 打印文档的内容
        System.out.println(getResponse); // 返回的全部内容和命令式一样的
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3、判断文档是否存在

    // 判断文档是否存在
    @Test
    public void testIsExists() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();

        GetRequest getRequest = new GetRequest("db_index1", "1");
        // 不获取返回的 _source 的上下文了
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");
        // 存在
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

4、增量更新文档记录

   /**
     * 增量更新文档记录(POST /索引名称/_update/id),文档必须存在。
     * @throws IOException
     */
    @Test
    public void testUpdateRequest() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
        // 构建文档数据
        UserVO userVO = new UserVO();
        userVO.setId(1L);
        userVO.setUserName("赵云update");
        userVO.setHeight(1.88D);
        userVO.setCreateTime(new Date());

        // 根据文档id修改
        UpdateRequest updateRequest = new UpdateRequest("db_index1", userVO.getId().toString());
        updateRequest.timeout("1s");
        // 将文档数据放入请求 json
        updateRequest.doc(JSON.toJSONString(userVO), XContentType.JSON);
        // 修改
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse.status()); // 对应命令返回的状态OK
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

5、删除文档

    // 删除文档记录(DELETE  //索引名称/_doc/id)
    @Test
    public void testDeleteRequest() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();
        DeleteRequest request = new DeleteRequest("db_index1", "1");
        request.timeout("1s");
        // 删除
        DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status()); // 对应命令返回的状态OK
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

6、批量操作文档数据

    @Test
    public void testBulkRequest() throws IOException {
        RestHighLevelClient restHighLevelClient = ESUtil.getRestHighLevelClient();

        // 构建批处理请求
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        for (int i = 1; i <= 5; i++) {
            UserVO userVO = new UserVO();
            userVO.setId(1L);
            userVO.setUserName("赵云batch" + i );
            userVO.setHeight(1.88D);
            userVO.setAge(10 + i);
            userVO.setCreateTime(new Date());

            // 批量添加/更新和批量删除,只需要修改对应的请求即可
            IndexRequest indexRequest = new IndexRequest("db_index2");
            indexRequest.id(userVO.getId().toString());
            indexRequest.source(JSON.toJSONString(userVO), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        //执行批处理请求
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures()); // 是否失败,返回 false 代表 成功!
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

– 求知若饥,虚心若愚。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/68666
推荐阅读
相关标签
  

闽ICP备14008679号