1.项目地址

https://github.com/GuardFTC/elasticsearch-test.git

2.cat常用命令整合

包括查看集群状态,查看集群索引信息、别名信息、节点信息等

  1. import cn.hutool.core.lang.Assert;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  4. import co.elastic.clients.elasticsearch.cat.*;
  5. import co.elastic.clients.elasticsearch.cat.aliases.AliasesRecord;
  6. import co.elastic.clients.elasticsearch.cat.health.HealthRecord;
  7. import co.elastic.clients.elasticsearch.cat.indices.IndicesRecord;
  8. import co.elastic.clients.elasticsearch.cat.master.MasterRecord;
  9. import co.elastic.clients.elasticsearch.cat.nodes.NodesRecord;
  10. import org.junit.jupiter.api.Test;
  11. import org.springframework.beans.factory.annotation.Qualifier;
  12. import org.springframework.boot.test.context.SpringBootTest;
  13. import javax.annotation.Resource;
  14. import java.io.IOException;
  15. import java.util.List;
  16. @SpringBootTest
  17. class ElasticSearchCatAndClusterTest {
  18. @Resource
  19. @Qualifier("primaryElasticsearchClient")
  20. private ElasticsearchClient primaryClient;
  21. @Test
  22. void testCat() throws IOException {
  23. //1.获取cat客户端
  24. ElasticsearchCatClient cat = primaryClient.cat();
  25. //2.获取集群健康状况
  26. HealthResponse health = cat.health();
  27. List<HealthRecord> healthRecords = health.valueBody();
  28. //3.结果校验
  29. Assert.isTrue(ObjectUtil.isNotNull(healthRecords));
  30. Assert.isTrue(1 == healthRecords.size());
  31. HealthRecord healthRecord = healthRecords.get(0);
  32. Assert.isTrue("ftc-es".equals(healthRecord.cluster()));
  33. Assert.isTrue("3".equals(healthRecord.nodeTotal()));
  34. //4.查询主节点信息并校验结果
  35. MasterResponse master = cat.master();
  36. List<MasterRecord> masterRecords = master.valueBody();
  37. Assert.isTrue(ObjectUtil.isNotNull(masterRecords));
  38. Assert.isTrue(1 == masterRecords.size());
  39. //5.查询集群节点信息
  40. NodesResponse nodes = cat.nodes();
  41. List<NodesRecord> nodesRecords = nodes.valueBody();
  42. Assert.isTrue(ObjectUtil.isNotNull(nodesRecords));
  43. Assert.isTrue(3 == nodesRecords.size());
  44. //6.查询集群别名信息
  45. AliasesResponse aliases = cat.aliases();
  46. List<AliasesRecord> aliasesRecords = aliases.valueBody();
  47. Assert.isTrue(ObjectUtil.isNotNull(aliasesRecords));
  48. //7.查询集群索引信息
  49. IndicesResponse indices = cat.indices();
  50. List<IndicesRecord> indicesRecords = indices.valueBody();
  51. Assert.isTrue(ObjectUtil.isNotNull(indicesRecords));
  52. }
  53. }

3.cluster常用命令整合

包括查看集群健康状态,查看集群统计信息,查看集群状态等

  1. import cn.hutool.core.lang.Assert;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  4. import co.elastic.clients.elasticsearch._types.HealthStatus;
  5. import co.elastic.clients.elasticsearch.cluster.ElasticsearchClusterClient;
  6. import co.elastic.clients.elasticsearch.cluster.StateResponse;
  7. import co.elastic.clients.json.JsonData;
  8. import jakarta.json.JsonObject;
  9. import org.junit.jupiter.api.Test;
  10. import org.springframework.beans.factory.annotation.Qualifier;
  11. import org.springframework.boot.test.context.SpringBootTest;
  12. import javax.annotation.Resource;
  13. import java.io.IOException;
  14. @SpringBootTest
  15. class ElasticSearchCatAndClusterTest {
  16. @Resource
  17. @Qualifier("primaryElasticsearchClient")
  18. private ElasticsearchClient primaryClient;
  19. @Test
  20. void testCluster() throws IOException {
  21. //1.获取cluster客户端
  22. ElasticsearchClusterClient cluster = primaryClient.cluster();
  23. //2.查询集群健康状态
  24. co.elastic.clients.elasticsearch.cluster.HealthResponse health = cluster.health();
  25. //3.校验集群健康状态信息
  26. Assert.isTrue(ObjectUtil.isNotNull(health));
  27. Assert.isTrue("ftc-es".equals(health.clusterName()));
  28. Assert.isTrue(3 == health.numberOfNodes());
  29. Assert.isTrue(HealthStatus.Green.jsonValue().equals(health.status().jsonValue()));
  30. //4.查询集群状态
  31. StateResponse state = cluster.state();
  32. JsonData jsonData = state.valueBody();
  33. //5.校验集群状态
  34. Assert.isTrue(ObjectUtil.isNotNull(jsonData));
  35. JsonObject status = jsonData.toJson().asJsonObject();
  36. Assert.isTrue("ftc-es".equals(status.getString("cluster_name")));
  37. Assert.isTrue(3 == status.getJsonObject("nodes").size());
  38. }
  39. }

4.索引常用命令整合

其实上述两个命令的整合,我本人并没有体验到JavaClientApi好用之处。直到索引整合这部分,哇哦!!!!!!这个客户端的API使用起来简直是太曼妙了!!!!!
我唯一想到的词就是曼妙!!!!!JavaClientApi把Elasticsearch的命令用java的形式完美的体现了出来。接下来上代码!!!!

创建索引

使用.indices().create()方法来创建索引。.indices()指定索引路由,.create()方法指定创建索引

创建索引无属性设置

  1. @Test
  2. void testCreateIndex() throws IOException {
  3. //1.创建无参索引
  4. CreateIndexResponse createIndexResponse = secondaryClient
  5. .indices()
  6. .create(i -> i.index(INDEX_NAME));
  7. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  8. }

索引别名设置

  1. @Test
  2. void testAlias() throws IOException {
  3. //1.创建无参索引
  4. CreateIndexResponse createIndexResponse = secondaryClient
  5. .indices()
  6. .create(i -> i.index(INDEX_NAME + "_1"));
  7. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  8. createIndexResponse = secondaryClient
  9. .indices()
  10. .create(i -> i.index(INDEX_NAME + "_2"));
  11. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  12. //2.多个索引添加一个别名
  13. PutAliasResponse putAliasResponse = secondaryClient
  14. .indices()
  15. .putAlias(a -> a
  16. .index(INDEX_NAME + "_1")
  17. .name(INDEX_NAME)
  18. );
  19. Assert.isTrue(putAliasResponse.acknowledged());
  20. //3.更新索引别名
  21. UpdateAliasesResponse updateAliasesResponse = secondaryClient
  22. .indices()
  23. .updateAliases(i -> i.actions(
  24. Action.of(a -> a.remove(
  25. r -> r.indices(INDEX_NAME + "_1").aliases(INDEX_NAME)
  26. )),
  27. Action.of(a -> a.add(
  28. r -> r.indices(INDEX_NAME + "_2").aliases(INDEX_NAME)
  29. ))
  30. ));
  31. Assert.isTrue(updateAliasesResponse.acknowledged());
  32. //4.删除别名
  33. DeleteAliasResponse deleteAliasResponse = secondaryClient
  34. .indices()
  35. .deleteAlias(i -> i
  36. .index(INDEX_NAME + "_1", INDEX_NAME + "_2")
  37. .name(CollUtil.newArrayList(INDEX_NAME))
  38. );
  39. Assert.isTrue(deleteAliasResponse.acknowledged());
  40. //5.查询别名
  41. GetAliasResponse alias = secondaryClient
  42. .indices()
  43. .getAlias(i -> i.index(INDEX_NAME + "_1", INDEX_NAME + "_2"));
  44. //6.校验查询结果
  45. Set<String> indexNames = alias.result().keySet();
  46. Assert.isTrue(2 == indexNames.size());
  47. indexNames.forEach(indexName -> {
  48. Set<String> aliases = alias.result().get(indexName).aliases().keySet();
  49. Assert.isTrue(0 == aliases.size());
  50. });
  51. }

创建索引时指定别名

  1. @Test
  2. void testCreateIndexWithAlias() throws IOException {
  3. //1.创建单个别名索引
  4. Alias alias = Alias.of(a -> a);
  5. CreateIndexResponse createIndexResponse = secondaryClient
  6. .indices()
  7. .create(i -> i
  8. .index(INDEX_NAME + "_1")
  9. .aliases(INDEX_NAME, alias)
  10. );
  11. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  12. //2.创建多个别名索引
  13. Map<String, Alias> aliasMap = MapUtil.newHashMap(2);
  14. aliasMap.put(INDEX_NAME, Alias.of(a -> a));
  15. aliasMap.put(INDEX_NAME + "_bak", Alias.of(a -> a));
  16. createIndexResponse = secondaryClient
  17. .indices()
  18. .create(i -> i
  19. .index(INDEX_NAME + "_2")
  20. .aliases(aliasMap)
  21. );
  22. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  23. //3.查询索引别名
  24. GetAliasResponse aliasResponse = secondaryClient
  25. .indices()
  26. .getAlias(i -> i.index(INDEX_NAME + "_1", INDEX_NAME + "_2"));
  27. //4.校验索引别名
  28. Map<String, IndexAliases> result = aliasResponse.result();
  29. Set<String> aliasNames = result.get(INDEX_NAME + "_1").aliases().keySet();
  30. Assert.isTrue("[\"test_index\"]".equals(JSONUtil.toJsonStr(aliasNames)));
  31. aliasNames = result.get(INDEX_NAME + "_2").aliases().keySet();
  32. Assert.isTrue("[\"test_index_bak\",\"test_index\"]".equals(JSONUtil.toJsonStr(aliasNames)));
  33. }

创建索引时指定mapping

直到这步,哇,真的,这种使用方法太曼妙了!!!!!

  1. @Test
  2. void testCreateIndexWithMapping() throws IOException {
  3. //1.创建索引
  4. CreateIndexResponse createIndexResponse = primaryClient
  5. .indices()
  6. .create(i -> i
  7. .index(INDEX_NAME)
  8. .mappings(m -> m
  9. .properties("name", p -> p.text(t -> t.analyzer("ik_max_word")))
  10. .properties("age", p -> p.integer(in -> in))
  11. .properties("tags", p -> p.keyword(k -> k))
  12. )
  13. );
  14. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  15. }

创建索引时指定setting

  1. @Test
  2. void testCreateIndexWithSetting() throws IOException {
  3. //1.创建索引
  4. CreateIndexResponse createIndexResponse = primaryClient
  5. .indices()
  6. .create(i -> i
  7. .index(INDEX_NAME)
  8. .settings(s -> s
  9. .refreshInterval(r -> r.time("1s"))
  10. .numberOfShards("3")
  11. .numberOfReplicas("1")
  12. )
  13. );
  14. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  15. }

创建索引时指定全部参数

  1. @Test
  2. void testCreateIndexWithAllArgs() throws IOException {
  3. //1.创建索引
  4. CreateIndexResponse createIndexResponse = secondaryClient
  5. .indices()
  6. .create(i -> i
  7. .index(INDEX_NAME + "_1")
  8. .aliases(INDEX_NAME, a -> a)
  9. .mappings(m -> m
  10. .properties("name", p -> p.text(t -> t.analyzer("ik_max_word")))
  11. .properties("age", p -> p.integer(in -> in))
  12. .properties("tags", p -> p.keyword(k -> k))
  13. )
  14. .settings(s -> s
  15. .refreshInterval(r -> r.time("1s"))
  16. .numberOfShards("3")
  17. .numberOfReplicas("1")
  18. )
  19. );
  20. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  21. }

查询索引

  1. @Test
  2. void testGetIndexes() throws IOException {
  3. //1.创建测试索引
  4. CreateIndexResponse response = primaryClient.indices().create(i -> i.index(INDEX_NAME));
  5. Assert.isTrue(Boolean.TRUE.equals(response.acknowledged()));
  6. //2.查询全部索引
  7. IndicesResponse indices = primaryClient.cat().indices();
  8. List<String> indexNames = CollStreamUtil.toList(indices.valueBody(), IndicesRecord::index);
  9. Assert.isTrue(indexNames.contains(INDEX_NAME));
  10. //3.查询单个索引
  11. GetIndexResponse getIndexResponse = primaryClient.indices().get(i -> i.index(INDEX_NAME));
  12. Map<String, IndexState> result = getIndexResponse.result();
  13. IndexState indexState = result.get(INDEX_NAME);
  14. Assert.isTrue(ObjectUtil.isNotNull(indexState));
  15. //4.获取索引单个属性
  16. Map<String, Alias> aliases = indexState.aliases();
  17. TypeMapping mappings = indexState.mappings();
  18. IndexSettings settings = indexState.settings();
  19. Assert.isTrue(ObjectUtil.isNotNull(aliases));
  20. Assert.isTrue(ObjectUtil.isNotNull(mappings));
  21. Assert.isTrue(ObjectUtil.isNotNull(settings));
  22. }

验证索引是否存在

  1. @Test
  2. void testExistIndex() throws IOException {
  3. //1.验证是否存在
  4. BooleanResponse exists = primaryClient.indices().exists(e -> e.index(INDEX_NAME));
  5. //2.校验结果
  6. Assert.isFalse(exists.value());
  7. }

删除索引

  1. @Test
  2. void testDeleteIndex() throws IOException {
  3. //1.创建索引
  4. CreateIndexResponse createIndexResponse = primaryClient
  5. .indices()
  6. .create(i -> i.index(INDEX_NAME));
  7. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  8. //2.验证是否存在
  9. BooleanResponse exists = primaryClient.indices().exists(e -> e.index(INDEX_NAME));
  10. Assert.isTrue(exists.value());
  11. //3.删除索引
  12. DeleteIndexResponse delete = primaryClient
  13. .indices()
  14. .delete(d -> d.index(INDEX_NAME));
  15. Assert.isTrue(delete.acknowledged());
  16. //4.验证是否存在
  17. exists = primaryClient.indices().exists(e -> e.index(INDEX_NAME));
  18. Assert.isFalse(exists.value());
  19. }

修改索引

在这一步,明确的体会到了,refresh的影响。因为之前是用kibana的Devtool,全程人工,所以refresh那点时间差是完全可以忽略的。
但是一旦到了代码的世界,那这1s简直就是一眼万年了。。。。

  1. @Test
  2. void testUpdateIndex() throws IOException, InterruptedException {
  3. //1.创建老索引
  4. CreateIndexResponse response = primaryClient
  5. .indices()
  6. .create(i -> i
  7. .index(INDEX_NAME + "_1")
  8. .aliases(INDEX_NAME, a -> a)
  9. .settings(s -> s
  10. .refreshInterval(r -> r.time("1s"))
  11. )
  12. );
  13. Assert.isTrue(Boolean.TRUE.equals(response.acknowledged()));
  14. //2.创建新索引
  15. response = primaryClient
  16. .indices()
  17. .create(i -> i
  18. .index(INDEX_NAME + "_2")
  19. .aliases(INDEX_NAME, a -> a)
  20. .settings(s -> s
  21. .refreshInterval(r -> r.time("1s"))
  22. .numberOfShards("3")
  23. .numberOfReplicas("1")
  24. )
  25. );
  26. Assert.isTrue(Boolean.TRUE.equals(response.acknowledged()));
  27. //3.老索引存入一条文档
  28. JSONObject entries = new JSONObject();
  29. entries.set("age", 1);
  30. IndexResponse index = primaryClient.index(i -> i
  31. .index(INDEX_NAME + "_1")
  32. .document(entries)
  33. );
  34. String id = index.id();
  35. Assert.isTrue(StrUtil.isNotBlank(id));
  36. //4.线程睡一会,给分片一个refresh的时间
  37. TimeUnit.SECONDS.sleep(1);
  38. //5.老索引数据迁移到新索引
  39. ReindexResponse reindex = primaryClient.reindex(r -> r
  40. .source(s -> s.index(INDEX_NAME + "_1"))
  41. .dest(d -> d.index(INDEX_NAME + "_2"))
  42. );
  43. Assert.isTrue(1 == reindex.batches());
  44. //6.删除老索引
  45. DeleteIndexResponse delete = primaryClient.indices().delete(d -> d.index(INDEX_NAME + "_1"));
  46. Assert.isTrue(delete.acknowledged());
  47. //7.验证老索引不存在
  48. BooleanResponse exists = primaryClient.indices().exists(e -> e.index(INDEX_NAME + "_1"));
  49. Assert.isFalse(exists.value());
  50. //8.线程再睡一会,给新索引一个refresh的时间
  51. TimeUnit.SECONDS.sleep(1);
  52. //9.查询数据在新索引
  53. SearchResponse<JSONObject> search = primaryClient.search(s -> s
  54. .index(INDEX_NAME + "_2")
  55. , JSONObject.class);
  56. String resultId = search.hits().hits().get(0).id();
  57. Assert.isTrue(id.equals(resultId));
  58. }

完整版单元测试

  1. import cn.hutool.core.collection.CollStreamUtil;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.lang.Assert;
  4. import cn.hutool.core.map.MapUtil;
  5. import cn.hutool.core.util.ObjectUtil;
  6. import cn.hutool.core.util.StrUtil;
  7. import cn.hutool.json.JSONObject;
  8. import cn.hutool.json.JSONUtil;
  9. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  10. import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
  11. import co.elastic.clients.elasticsearch.cat.IndicesResponse;
  12. import co.elastic.clients.elasticsearch.cat.indices.IndicesRecord;
  13. import co.elastic.clients.elasticsearch.core.IndexResponse;
  14. import co.elastic.clients.elasticsearch.core.ReindexResponse;
  15. import co.elastic.clients.elasticsearch.core.SearchResponse;
  16. import co.elastic.clients.elasticsearch.indices.*;
  17. import co.elastic.clients.elasticsearch.indices.get_alias.IndexAliases;
  18. import co.elastic.clients.elasticsearch.indices.update_aliases.Action;
  19. import co.elastic.clients.transport.endpoints.BooleanResponse;
  20. import org.junit.jupiter.api.BeforeEach;
  21. import org.junit.jupiter.api.Test;
  22. import org.springframework.beans.factory.annotation.Qualifier;
  23. import org.springframework.boot.test.context.SpringBootTest;
  24. import javax.annotation.Resource;
  25. import java.io.IOException;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Set;
  29. import java.util.concurrent.TimeUnit;
  30. import java.util.stream.Collectors;
  31. @SpringBootTest
  32. class ElasticSearchIndexTest {
  33. @Resource
  34. @Qualifier("primaryElasticsearchClient")
  35. private ElasticsearchClient primaryClient;
  36. @Resource
  37. @Qualifier("secondaryElasticsearchClient")
  38. private ElasticsearchClient secondaryClient;
  39. /**
  40. * 测试Mock索引名称常量
  41. */
  42. private static final String INDEX_NAME = "test_index";
  43. @BeforeEach
  44. void removeApplicationIndex() throws IOException {
  45. //1.查询所有索引
  46. IndicesResponse catIndies = primaryClient.cat().indices();
  47. List<IndicesRecord> indicesRecords = catIndies.valueBody();
  48. //2.获取所有自定义索引名称
  49. List<String> applicationIndexNames = indicesRecords.stream()
  50. .map(IndicesRecord::index)
  51. .filter(index -> !index.startsWith(StrUtil.DOT))
  52. .collect(Collectors.toList());
  53. //3.判空返回
  54. if (CollUtil.isEmpty(applicationIndexNames)) {
  55. return;
  56. }
  57. //4.删除
  58. ElasticsearchIndicesClient indicesClient = primaryClient.indices();
  59. DeleteIndexResponse delete = indicesClient.delete(i -> i.index(applicationIndexNames));
  60. Assert.isTrue(delete.acknowledged());
  61. }
  62. @Test
  63. void testCreateIndex() throws IOException {
  64. //1.创建无参索引
  65. CreateIndexResponse createIndexResponse = secondaryClient
  66. .indices()
  67. .create(i -> i.index(INDEX_NAME));
  68. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  69. }
  70. @Test
  71. void testAlias() throws IOException {
  72. //1.创建无参索引
  73. CreateIndexResponse createIndexResponse = secondaryClient
  74. .indices()
  75. .create(i -> i.index(INDEX_NAME + "_1"));
  76. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  77. createIndexResponse = secondaryClient
  78. .indices()
  79. .create(i -> i.index(INDEX_NAME + "_2"));
  80. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  81. //2.多个索引添加一个别名
  82. PutAliasResponse putAliasResponse = secondaryClient
  83. .indices()
  84. .putAlias(a -> a
  85. .index(INDEX_NAME + "_1")
  86. .name(INDEX_NAME)
  87. );
  88. Assert.isTrue(putAliasResponse.acknowledged());
  89. //3.更新索引别名
  90. UpdateAliasesResponse updateAliasesResponse = secondaryClient
  91. .indices()
  92. .updateAliases(i -> i.actions(
  93. Action.of(a -> a.remove(
  94. r -> r.indices(INDEX_NAME + "_1").aliases(INDEX_NAME)
  95. )),
  96. Action.of(a -> a.add(
  97. r -> r.indices(INDEX_NAME + "_2").aliases(INDEX_NAME)
  98. ))
  99. ));
  100. Assert.isTrue(updateAliasesResponse.acknowledged());
  101. //4.删除别名
  102. DeleteAliasResponse deleteAliasResponse = secondaryClient
  103. .indices()
  104. .deleteAlias(i -> i
  105. .index(INDEX_NAME + "_1", INDEX_NAME + "_2")
  106. .name(CollUtil.newArrayList(INDEX_NAME))
  107. );
  108. Assert.isTrue(deleteAliasResponse.acknowledged());
  109. //5.查询别名
  110. GetAliasResponse alias = secondaryClient
  111. .indices()
  112. .getAlias(i -> i.index(INDEX_NAME + "_1", INDEX_NAME + "_2"));
  113. //6.校验查询结果
  114. Set<String> indexNames = alias.result().keySet();
  115. Assert.isTrue(2 == indexNames.size());
  116. indexNames.forEach(indexName -> {
  117. Set<String> aliases = alias.result().get(indexName).aliases().keySet();
  118. Assert.isTrue(0 == aliases.size());
  119. });
  120. }
  121. @Test
  122. void testCreateIndexWithAlias() throws IOException {
  123. //1.创建单个别名索引
  124. Alias alias = Alias.of(a -> a);
  125. CreateIndexResponse createIndexResponse = secondaryClient
  126. .indices()
  127. .create(i -> i
  128. .index(INDEX_NAME + "_1")
  129. .aliases(INDEX_NAME, alias)
  130. );
  131. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  132. //2.创建多个别名索引
  133. Map<String, Alias> aliasMap = MapUtil.newHashMap(2);
  134. aliasMap.put(INDEX_NAME, Alias.of(a -> a));
  135. aliasMap.put(INDEX_NAME + "_bak", Alias.of(a -> a));
  136. createIndexResponse = secondaryClient
  137. .indices()
  138. .create(i -> i
  139. .index(INDEX_NAME + "_2")
  140. .aliases(aliasMap)
  141. );
  142. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  143. //3.查询索引别名
  144. GetAliasResponse aliasResponse = secondaryClient
  145. .indices()
  146. .getAlias(i -> i.index(INDEX_NAME + "_1", INDEX_NAME + "_2"));
  147. //4.校验索引别名
  148. Map<String, IndexAliases> result = aliasResponse.result();
  149. Set<String> aliasNames = result.get(INDEX_NAME + "_1").aliases().keySet();
  150. Assert.isTrue("[\"test_index\"]".equals(JSONUtil.toJsonStr(aliasNames)));
  151. aliasNames = result.get(INDEX_NAME + "_2").aliases().keySet();
  152. Assert.isTrue("[\"test_index_bak\",\"test_index\"]".equals(JSONUtil.toJsonStr(aliasNames)));
  153. }
  154. @Test
  155. void testCreateIndexWithMapping() throws IOException {
  156. //1.创建索引
  157. CreateIndexResponse createIndexResponse = primaryClient
  158. .indices()
  159. .create(i -> i
  160. .index(INDEX_NAME)
  161. .mappings(m -> m
  162. .properties("name", p -> p.text(t -> t.analyzer("ik_max_word")))
  163. .properties("age", p -> p.integer(in -> in))
  164. .properties("tags", p -> p.keyword(k -> k))
  165. )
  166. );
  167. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  168. }
  169. @Test
  170. void testCreateIndexWithSetting() throws IOException {
  171. //1.创建索引
  172. CreateIndexResponse createIndexResponse = primaryClient
  173. .indices()
  174. .create(i -> i
  175. .index(INDEX_NAME)
  176. .settings(s -> s
  177. .refreshInterval(r -> r.time("1s"))
  178. .numberOfShards("3")
  179. .numberOfReplicas("1")
  180. )
  181. );
  182. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  183. }
  184. @Test
  185. void testCreateIndexWithAllArgs() throws IOException {
  186. //1.创建索引
  187. CreateIndexResponse createIndexResponse = secondaryClient
  188. .indices()
  189. .create(i -> i
  190. .index(INDEX_NAME + "_1")
  191. .aliases(INDEX_NAME, a -> a)
  192. .mappings(m -> m
  193. .properties("name", p -> p.text(t -> t.analyzer("ik_max_word")))
  194. .properties("age", p -> p.integer(in -> in))
  195. .properties("tags", p -> p.keyword(k -> k))
  196. )
  197. .settings(s -> s
  198. .refreshInterval(r -> r.time("1s"))
  199. .numberOfShards("3")
  200. .numberOfReplicas("1")
  201. )
  202. );
  203. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  204. }
  205. @Test
  206. void testGetIndexes() throws IOException {
  207. //1.创建测试索引
  208. CreateIndexResponse response = primaryClient.indices().create(i -> i.index(INDEX_NAME));
  209. Assert.isTrue(Boolean.TRUE.equals(response.acknowledged()));
  210. //2.查询全部索引
  211. IndicesResponse indices = primaryClient.cat().indices();
  212. List<String> indexNames = CollStreamUtil.toList(indices.valueBody(), IndicesRecord::index);
  213. Assert.isTrue(indexNames.contains(INDEX_NAME));
  214. //3.查询单个索引
  215. GetIndexResponse getIndexResponse = primaryClient.indices().get(i -> i.index(INDEX_NAME));
  216. Map<String, IndexState> result = getIndexResponse.result();
  217. IndexState indexState = result.get(INDEX_NAME);
  218. Assert.isTrue(ObjectUtil.isNotNull(indexState));
  219. //4.获取索引单个属性
  220. Map<String, Alias> aliases = indexState.aliases();
  221. TypeMapping mappings = indexState.mappings();
  222. IndexSettings settings = indexState.settings();
  223. Assert.isTrue(ObjectUtil.isNotNull(aliases));
  224. Assert.isTrue(ObjectUtil.isNotNull(mappings));
  225. Assert.isTrue(ObjectUtil.isNotNull(settings));
  226. }
  227. @Test
  228. void testExistIndex() throws IOException {
  229. //1.验证是否存在
  230. BooleanResponse exists = primaryClient.indices().exists(e -> e.index(INDEX_NAME));
  231. //2.校验结果
  232. Assert.isFalse(exists.value());
  233. }
  234. @Test
  235. void testDeleteIndex() throws IOException {
  236. //1.创建索引
  237. CreateIndexResponse createIndexResponse = primaryClient
  238. .indices()
  239. .create(i -> i.index(INDEX_NAME));
  240. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  241. //2.验证是否存在
  242. BooleanResponse exists = primaryClient.indices().exists(e -> e.index(INDEX_NAME));
  243. Assert.isTrue(exists.value());
  244. //3.删除索引
  245. DeleteIndexResponse delete = primaryClient
  246. .indices()
  247. .delete(d -> d.index(INDEX_NAME));
  248. Assert.isTrue(delete.acknowledged());
  249. //4.验证是否存在
  250. exists = primaryClient.indices().exists(e -> e.index(INDEX_NAME));
  251. Assert.isFalse(exists.value());
  252. }
  253. @Test
  254. void testUpdateIndex() throws IOException, InterruptedException {
  255. //1.创建老索引
  256. CreateIndexResponse response = primaryClient
  257. .indices()
  258. .create(i -> i
  259. .index(INDEX_NAME + "_1")
  260. .aliases(INDEX_NAME, a -> a)
  261. .settings(s -> s
  262. .refreshInterval(r -> r.time("1s"))
  263. )
  264. );
  265. Assert.isTrue(Boolean.TRUE.equals(response.acknowledged()));
  266. //2.创建新索引
  267. response = primaryClient
  268. .indices()
  269. .create(i -> i
  270. .index(INDEX_NAME + "_2")
  271. .aliases(INDEX_NAME, a -> a)
  272. .settings(s -> s
  273. .refreshInterval(r -> r.time("1s"))
  274. .numberOfShards("3")
  275. .numberOfReplicas("1")
  276. )
  277. );
  278. Assert.isTrue(Boolean.TRUE.equals(response.acknowledged()));
  279. //3.老索引存入一条文档
  280. JSONObject entries = new JSONObject();
  281. entries.set("age", 1);
  282. IndexResponse index = primaryClient.index(i -> i
  283. .index(INDEX_NAME + "_1")
  284. .document(entries)
  285. );
  286. String id = index.id();
  287. Assert.isTrue(StrUtil.isNotBlank(id));
  288. //4.线程睡一会,给分片一个refresh的时间
  289. TimeUnit.SECONDS.sleep(1);
  290. //5.老索引数据迁移到新索引
  291. ReindexResponse reindex = primaryClient.reindex(r -> r
  292. .source(s -> s.index(INDEX_NAME + "_1"))
  293. .dest(d -> d.index(INDEX_NAME + "_2"))
  294. );
  295. Assert.isTrue(1 == reindex.batches());
  296. //6.删除老索引
  297. DeleteIndexResponse delete = primaryClient.indices().delete(d -> d.index(INDEX_NAME + "_1"));
  298. Assert.isTrue(delete.acknowledged());
  299. //7.验证老索引不存在
  300. BooleanResponse exists = primaryClient.indices().exists(e -> e.index(INDEX_NAME + "_1"));
  301. Assert.isFalse(exists.value());
  302. //8.线程再睡一会,给新索引一个refresh的时间
  303. TimeUnit.SECONDS.sleep(1);
  304. //9.查询数据在新索引
  305. SearchResponse<JSONObject> search = primaryClient.search(s -> s
  306. .index(INDEX_NAME + "_2")
  307. , JSONObject.class);
  308. String resultId = search.hits().hits().get(0).id();
  309. Assert.isTrue(id.equals(resultId));
  310. }
  311. }