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

    

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值