ElasticSearch6.x基于SpringBoot 实现ElasticSearch的索引管理

小虾米 阅读:630 2021-03-31 17:03:14 评论:0

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"); 
	} 
} 
 
     

 

标签:Spring Boot
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号