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

灰太狼 2023-10-18 22:21 188阅读 0赞

SpringBoot 功能封装涉及ElasticSearch的索引管理方法约定如下:

indexExist(String index):判断指定index 是否存在

createIndex(String indexName):创建索引

createInde(String indexName, String type):创建索引

indexDelete(String index):索引删除

在上一篇文中说到:ElasticSearch6.x 基于SpringBoot 实现ElasticSearch连接功能封装,将约定的方法填充到ElasticSearchIndexUtil.java 工具类中。

  1. @Component
  2. public class ElasticSearchIndexUtil {
  3. // 引入 Ela 连接实列化对象
  4. @Autowired
  5. private TransportClient client;
  6. /**
  7. * 功能描述:新建索引
  8. *
  9. * @param indexName
  10. * 索引名
  11. */
  12. public boolean createIndex(String indexName) {
  13. // 使用默认设置的type
  14. CreateIndexResponse response = client.admin().indices().create(new CreateIndexRequest(indexName)).actionGet();
  15. String index = response.index();
  16. return indexExist(index);
  17. }
  18. /**
  19. * 功能描述:新建索引
  20. *
  21. * @param indexName
  22. * 索引名
  23. * @param type
  24. * 索引类型
  25. */
  26. public boolean createInde(String indexName, String type) throws InterruptedException, ExecutionException {
  27. IndexResponse response = client.prepareIndex(indexName, type).execute().get();
  28. if (response != null) {
  29. String index = response.getIndex();
  30. return indexExist(index);
  31. }
  32. return false;
  33. }
  34. /**
  35. * 功能描述:验证索引是否存在
  36. *
  37. * @param index
  38. * 索引名
  39. */
  40. public boolean indexExist(String index) {
  41. IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(index);
  42. IndicesExistsResponse inExistsResponse = client.admin().indices().exists(inExistsRequest).actionGet();
  43. return inExistsResponse.isExists();
  44. }
  45. /**
  46. * 功能描述:索引删除
  47. * @param index
  48. * @return
  49. */
  50. public boolean indexDelete(String index) {
  51. DeleteIndexResponse deleteResponse = client.admin().indices()
  52. .prepareDelete(index.toLowerCase())
  53. .execute()
  54. .actionGet();
  55. return deleteResponse.isAcknowledged()?true:false;
  56. }
  57. }

编写测试工具类Test.java ,测试相关封装的功能代码:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
  4. @WebAppConfiguration
  5. public class Test {
  6. @Autowired
  7. private ElasticSearchIndexUtil util;
  8. @org.junit.Test
  9. public void createIndex() {
  10. util.createIndex("username");
  11. }
  12. @org.junit.Test
  13. public void createIndexTwo() {
  14. util.createIndex("website","blog");
  15. }
  16. @org.junit.Test
  17. public void indexExist() {
  18. util.indexExist("username");
  19. }
  20. @org.junit.Test
  21. public void indexDelete() {
  22. util.indexDelete("username");
  23. }
  24. }

发表评论

表情:
评论列表 (有 0 条评论,188人围观)

还没有评论,来说两句吧...

相关阅读