判断Elasticsearch中的索引是否存在工具类

1.工具类如下:

package net.longjin.comm.utils;
import net.longjin.comm.es.ElasticConfigration;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 描述:判断ES中的索引是否存在工具类
 *
 * @author 何志鹏
 * @ClassName:ElasticsearchUtils
 * @create 2019-07-04 16:29
 * Version 1.0
 */
@Component
public class ElasticsearchUtils {

    @Autowired
    private ElasticConfigration elasticConfigration;



    public   boolean isExistIndex(String indexName){
        Client client = elasticConfigration.client();
        boolean flag = false;
        try {
            if(client != null){
                flag =client.admin().indices().exists(
                        new IndicesExistsRequest()
                                .indices(new String[]{indexName}))
                        .actionGet().isExists();

            }
        } catch (ElasticsearchException e) {
            e.printStackTrace();
        }

        return flag;
    }


}

2.具体调用方法如下:

//判断索引是否存在 不存在的话则创建索引
boolean caseworkfileinformationlog = elasticsearchUtils.isExistIndex("caseworkfileinformationlog");
if(!caseworkfileinformationlog){
    CreateIndexRequest cIndexRequest = new CreateIndexRequest("caseworkfileinformationlog");
    CreateIndexResponse cIndexResponse = client.admin().indices().create(cIndexRequest)
            .actionGet();
}

3.此工具类在我实际项目的应用场景为:当在开发测试阶段时   时常会去直接删ES的索引库  而每条数据只能插入一条   所以得先查询该条数据是否有添加过   由于没有这个判断索引是否存在  则每次报索引不存在的错误

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值