RestClient操作ElasticSearch

  • put
  	@Autowired
    RestClientBuilder restClientBuilder;
    @Test
    void elasticSearchRestClientPut() {
        Employee employee = new Employee(1, "xiaoming", "xiaoming@163.com");

        // RestClient put
        RestClient restClient = restClientBuilder.build();
        Request request = new Request("PUT", "/com1/employee/1");
        request.setJsonEntity(JSON.toJSONString(employee));
        Response response = null;
        try {
            response = restClient.performRequest(request);
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • get
@Test
void elasticSearchRestClientGet(){
    // RestClient get
    RestClient restClient = restClientBuilder.build();
    Request request = new Request("GET", "/com1/_search");
    String query = "{\n" +
            "    \"query\" : {\n" +
            "        \"match\" : {\n" +
            "            \"name\" : \"xiao\"\n" +
            "        }\n" +
            "    }\n" +
            "}";
    request.setJsonEntity(query);
    Response response = null;
    try {
        response = restClient.performRequest(request);
        String string = EntityUtils.toString(response.getEntity());
        System.out.println(string);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
  • head
@Test
void elasticSearchRestClientHead(){
    // RestClient head 验证是否存在
    // 存在 Response{requestLine=HEAD /com1/employee/1 HTTP/1.1, host=http://172.16.0.173:9200, response=HTTP/1.1 200 OK}
    // 不存在 Response{requestLine=HEAD /com1/employee/3 HTTP/1.1, host=http://172.16.0.173:9200, response=HTTP/1.1 404 Not Found}
    RestClient restClient = restClientBuilder.build();
    Request request = new Request("HEAD", "/com1/employee/1");
    Response response = null;
    try {
        response = restClient.performRequest(request);
        System.out.println(response);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
  • delete
@Test
void elasticSearchRestClientDelete(){
    // RestClient delete 验证是否存在
    RestClient restClient = restClientBuilder.build();
    Request request = new Request("DELETE", "/com1/employee/3");
    Response response = null;
    try {
        response = restClient.performRequest(request);
        System.out.println(response);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值