ElasticSearch6.x基于SpringBoot 实现ElasticSearch的索引管理
SpringBoot 功能封装涉及ElasticSearch的索引管理方法约定如下:
indexExist(String index):判断指定index 是否存在
createIndex(String indexName):创建索引
createInde(String indexName, String type):创建索引
indexDelete(String index):索引删除
在上一篇文中说到:ElasticSearch6.x 基于SpringBoot 实现ElasticSearch连接功能封装,将约定的方法填充到ElasticSearchIndexUtil.java 工具类中。
@Component
public class ElasticSearchIndexUtil {
// 引入 Ela 连接实列化对象
@Autowired
private TransportClient client;
/**
* 功能描述:新建索引
*
* @param indexName
* 索引名
*/
public boolean createIndex(String indexName) {
// 使用默认设置的type
CreateIndexResponse response = client.admin().indices().create(new CreateIndexRequest(indexName)).actionGet();
String index = response.index();
return indexExist(index);
}
/**
* 功能描述:新建索引
*
* @param indexName
* 索引名
* @param type
* 索引类型
*/
public boolean createInde(String indexName, String type) throws InterruptedException, ExecutionException {
IndexResponse response = client.prepareIndex(indexName, type).execute().get();
if (response != null) {
String index = response.getIndex();
return indexExist(index);
}
return false;
}
/**
* 功能描述:验证索引是否存在
*
* @param index
* 索引名
*/
public boolean indexExist(String index) {
IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(index);
IndicesExistsResponse inExistsResponse = client.admin().indices().exists(inExistsRequest).actionGet();
return inExistsResponse.isExists();
}
/**
* 功能描述:索引删除
* @param index
* @return
*/
public boolean indexDelete(String index) {
DeleteIndexResponse deleteResponse = client.admin().indices()
.prepareDelete(index.toLowerCase())
.execute()
.actionGet();
return deleteResponse.isAcknowledged()?true:false;
}
}
编写测试工具类Test.java ,测试相关封装的功能代码:
@RunWith(SpringRunner.class)
@SpringBootTest
// 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
@WebAppConfiguration
public class Test {
@Autowired
private ElasticSearchIndexUtil util;
@org.junit.Test
public void createIndex() {
util.createIndex("username");
}
@org.junit.Test
public void createIndexTwo() {
util.createIndex("website","blog");
}
@org.junit.Test
public void indexExist() {
util.indexExist("username");
}
@org.junit.Test
public void indexDelete() {
util.indexDelete("username");
}
}
还没有评论,来说两句吧...