Elasticsearch判断index是否存在--java实现

在做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);
	}
}


  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值