Java客户端如何直接调用es的API
一. 问题
今天做项目的时候,想要直接通过java客户端调用es的api创建策略
PUT {{url}}/_ilm/policy/test_policy
{
"policy": {
"phases": {
"hot": {
"min_age": "0ms",
"actions": {
"rollover": {
"max_docs": 1000000
}
}
}
}
}
}
我的项目是用springboot写的,通过以下依赖来创建es的客户端
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.11.4</version>
<scope>compile</scope>
</dependency>
那么我们怎么使用这个客户端直接通过发送json请求体的方式与es交互呢?
二. withJson
我去看了一眼官方文档 ,它可以通过withJson来调用
所以我们可以根据它的列子来编写代码,具体代码如下
String policyName = "max_docs_policy";
Reader policyBody = new StringReader("{\n" +
" \"policy\": {\n" +
" \"phases\": {\n" +
" \"hot\": {\n" +
" \"min_age\": \"0ms\",\n" +
" \"actions\": {\n" +
" \"rollover\": {\n" +
" \"max_docs\": 1000000\n" +
" }\n" +
" }\n" +
" },\n" +
" \"warm\": {\n" +
" \"min_age\": \"30d\",\n" +
" \"actions\": {\n" +
" \"set_priority\": {\n" +
" \"priority\": 50\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }");
try {
// 判断策略是否存在
elasticsearchManageClient.ilm().getLifecycle(g->g.name(policyName));
} catch (Exception e) {
// 不存在就创建
elasticsearchManageClient.ilm().putLifecycle(l->l.name(policyName).withJson(policyBody));
}
通过以上代码就能够创建指定的策略了