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的索引库 而每条数据只能插入一条 所以得先查询该条数据是否有添加过 由于没有这个判断索引是否存在 则每次报索引不存在的错误