在做Elasticsearch相关开发的时候,有个地方需要用java判断index在集群中是否存在,于是在Elasticsearch java api中找了半天,总算是找到了,记录下来,方便自己,也方便别人。
java实现代码:
import java.net.InetAddress;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.plugin.deletebyquery.DeleteByQueryPlugin;
public class Elasticsearch {
private Client client;
private IndicesAdminClient adminClient;
private void init() throws Exception{
Settings settings = Settings.settingsBuilder().put("cluster.name", "log-test")
.build();
client = TransportClient.builder().settings(settings)
.addPlugin(DeleteByQueryPlugin.class)
.build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("172.17.6.202"), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("172.17.6.203"), 9300));
}
public Elasticsearch() {
try {
init();
} catch (Exception e) {
System.out.println("init() exception!");
e.printStackTrace();
}
adminClient = client.admin().indices();
}
public boolean indexExists(String index){
IndicesExistsRequest request = new IndicesExistsRequest(index);
IndicesExistsResponse response = adminClient.exists(request).actionGet();
if (response.isExists()) {
return true;
}
return false;
}
public static void main(String[] args) {
Elasticsearch es = new Elasticsearch();
boolean exists = es.indexExists("index1");
System.out.println(exists);
}
}