1.项目地址

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

2.文档API命令整合

创建实体类

  1. import lombok.Data;
  2. /**
  3. * @author: 冯铁城 [17615007230@163.com]
  4. * @date: 2022-08-22 11:16:43
  5. * @describe: 学生类
  6. */
  7. @Data
  8. public class Student {
  9. /**
  10. * 主键ID
  11. */
  12. private Integer id;
  13. /**
  14. * 名称
  15. */
  16. private String name;
  17. /**
  18. * 年龄
  19. */
  20. private Integer age;
  21. }

存储单个文档

使用.index方法控制

  1. @Test
  2. void createDocSingle() throws IOException {
  3. //1.创建学生对象
  4. Student student = new Student();
  5. student.setId(1);
  6. student.setName("冯铁城");
  7. student.setAge(11);
  8. //2.创建单个文档不指定ID
  9. IndexResponse indexResponse = primaryClient.index(i -> i
  10. .index(INDEX_NAME)
  11. .document(student)
  12. );
  13. Result result = indexResponse.result();
  14. Assert.isTrue("created".equals(result.jsonValue().toLowerCase(Locale.ROOT)));
  15. //3.创建单个文档指定ID
  16. indexResponse = primaryClient.index(i -> i
  17. .index(INDEX_NAME)
  18. .document(student)
  19. .id("1")
  20. );
  21. result = indexResponse.result();
  22. Assert.isTrue("created".equals(result.jsonValue().toLowerCase(Locale.ROOT)));
  23. //4.创建单个文档进行ID唯一性控制
  24. String errorMessage = null;
  25. try {
  26. primaryClient.index(i -> i
  27. .index(INDEX_NAME)
  28. .document(student)
  29. .id("1")
  30. .opType(OpType.Create)
  31. );
  32. } catch (Exception e) {
  33. errorMessage = e.getMessage();
  34. }
  35. Assert.isTrue(ObjectUtil.isNotNull(errorMessage));
  36. Assert.isTrue(errorMessage.contains("version_conflict_engine_exception"));
  37. }

存储多个文档

  1. @Test
  2. void createDocBulk() throws IOException {
  3. //1.创建学生对象
  4. Student student = new Student();
  5. student.setId(1);
  6. student.setName("张钰玲");
  7. student.setAge(11);
  8. //2.批量保存数据不带ID
  9. BulkResponse bulk = primaryClient.bulk(b -> b
  10. .index(INDEX_NAME)
  11. .operations(o -> o.create(c -> c.document(student)))
  12. .operations(o -> o.create(c -> c.document(student)))
  13. );
  14. Assert.isFalse(bulk.errors());
  15. Assert.isTrue(2 == bulk.items().size());
  16. //3.批量保存数据带ID
  17. bulk = primaryClient.bulk(b -> b
  18. .index(INDEX_NAME)
  19. .operations(o -> o.create(c -> c.document(student).id("1")))
  20. .operations(o -> o.create(c -> c.document(student).id("2")))
  21. );
  22. Assert.isFalse(bulk.errors());
  23. Assert.isTrue(2 == bulk.items().size());
  24. }

查询文档

  1. @Test
  2. void getDocSingle() throws IOException {
  3. //1.创建学生对象
  4. Student student = new Student();
  5. student.setId(1);
  6. student.setName("冯铁城");
  7. student.setAge(18);
  8. Student studentBak = new Student();
  9. student.setId(2);
  10. student.setName("张钰玲");
  11. student.setAge(16);
  12. //2.批量保存数据
  13. BulkResponse bulk = secondaryClient.bulk(b -> b
  14. .index(INDEX_NAME)
  15. .operations(o -> o.create(c -> c.document(student).id("1")))
  16. .operations(o -> o.create(c -> c.document(studentBak).id("2")))
  17. .refresh(Refresh.True)
  18. );
  19. Assert.isFalse(bulk.errors());
  20. Assert.isTrue(2 == bulk.items().size());
  21. //3.根据ID查询单个数据
  22. Student source = secondaryClient.get(g -> g
  23. .index(INDEX_NAME)
  24. .id("1"), Student.class
  25. ).source();
  26. Assert.isTrue(JSONUtil.toJsonStr(student).equals(JSONUtil.toJsonStr(source)));
  27. //4.按照ID批量查询
  28. List<MultiGetResponseItem<Student>> docs = secondaryClient.mget(m -> m
  29. .index(INDEX_NAME)
  30. .ids("1", "2"), Student.class
  31. ).docs();
  32. Assert.isTrue(2 == docs.size());
  33. Student source1 = docs.get(0).result().source();
  34. Assert.isTrue(JSONUtil.toJsonStr(student).equals(JSONUtil.toJsonStr(source1)));
  35. Student source2 = docs.get(1).result().source();
  36. Assert.isTrue(JSONUtil.toJsonStr(studentBak).equals(JSONUtil.toJsonStr(source2)));
  37. }

判定文档是否存在

  1. @Test
  2. void existDoc() throws IOException {
  3. //1.验证数据存在
  4. BooleanResponse exists = secondaryClient.exists(e -> e
  5. .index(INDEX_NAME)
  6. .id(DEFAULT_ID)
  7. );
  8. Assert.isTrue(exists.value());
  9. //2.验证数据不存在
  10. exists = secondaryClient.exists(e -> e
  11. .index(INDEX_NAME)
  12. .id(DEFAULT_ID + "1")
  13. );
  14. Assert.isFalse(exists.value());
  15. }

修改文档单个

  1. @Test
  2. void updateDocSingle() throws IOException {
  3. //1.查询默认数据
  4. Student student = primaryClient.get(g -> g
  5. .index(INDEX_NAME)
  6. .id(DEFAULT_ID), Student.class
  7. ).source();
  8. Assert.isTrue(ObjectUtil.isNotNull(student));
  9. //2.全量更新单个数据(立即refresh,为了单元测试方便)
  10. student.setAge(100);
  11. IndexResponse index = primaryClient.index(i -> i
  12. .index(INDEX_NAME)
  13. .document(student)
  14. .id(DEFAULT_ID)
  15. .refresh(Refresh.True)
  16. );
  17. Assert.isTrue("updated".equals(index.result().jsonValue().toLowerCase(Locale.ROOT)));
  18. //3.查询校验
  19. Integer age = primaryClient.get(g -> g
  20. .index(INDEX_NAME)
  21. .id(DEFAULT_ID), Student.class
  22. ).source().getAge();
  23. Assert.isTrue(100 == age);
  24. //4.全量更新单个数据并进行版本控制(立即refresh,为了单元测试方便)
  25. student.setAge(11);
  26. long primaryTerm = index.primaryTerm();
  27. long seqNo = index.seqNo();
  28. index = primaryClient.index(i -> i
  29. .index(INDEX_NAME)
  30. .document(student)
  31. .id(DEFAULT_ID)
  32. .ifPrimaryTerm(primaryTerm)
  33. .ifSeqNo(seqNo)
  34. .refresh(Refresh.True)
  35. );
  36. Assert.isTrue("updated".equals(index.result().jsonValue().toLowerCase(Locale.ROOT)));
  37. //5.查询校验
  38. age = primaryClient.get(g -> g
  39. .index(INDEX_NAME)
  40. .id(DEFAULT_ID), Student.class
  41. ).source().getAge();
  42. Assert.isTrue(11 == age);
  43. //6.全量更新单个数据并进行版本控制(立即refresh,为了单元测试方便)
  44. String errorMessage = null;
  45. try {
  46. primaryClient.index(i -> i
  47. .index(INDEX_NAME)
  48. .document(student)
  49. .id(INDEX_NAME)
  50. .ifPrimaryTerm((long) 1)
  51. .ifSeqNo((long) 2)
  52. .refresh(Refresh.True)
  53. );
  54. } catch (Exception e) {
  55. errorMessage = e.getMessage();
  56. }
  57. Assert.isTrue(StrUtil.isNotBlank(errorMessage));
  58. Assert.isTrue(errorMessage.contains("version_conflict_engine_exception"));
  59. //7.更新文档部分属性
  60. Student studentBak = new Student();
  61. studentBak.setAge(30);
  62. UpdateResponse<Student> update = primaryClient.update(u -> u
  63. .index(INDEX_NAME)
  64. .id(DEFAULT_ID)
  65. .doc(studentBak)
  66. .refresh(Refresh.True), Student.class
  67. );
  68. Assert.isTrue("updated".equals(update.result().jsonValue().toLowerCase(Locale.ROOT)));
  69. //8.查询校验
  70. Student source = primaryClient.get(g -> g
  71. .index(INDEX_NAME)
  72. .id(DEFAULT_ID), Student.class
  73. ).source();
  74. Assert.isTrue(ObjectUtil.isNotNull(source));
  75. Assert.isTrue(studentBak.getAge() == source.getAge());
  76. Assert.isTrue(student.getName().equals(source.getName()));
  77. }

修改文档批量

  1. @Test
  2. void updateDocBulk() throws IOException {
  3. //1.准备测试数据
  4. Student student = new Student();
  5. student.setName("冯铁城");
  6. student.setAge(18);
  7. Student studentBak = new Student();
  8. studentBak.setName("张钰玲");
  9. studentBak.setAge(16);
  10. //2.存入测试数据
  11. BulkResponse bulk = primaryClient.bulk(b -> b
  12. .index(INDEX_NAME)
  13. .operations(o -> o.create(c -> c.document(student).id("1")))
  14. .operations(o -> o.create(c -> c.document(studentBak).id("2")))
  15. );
  16. Assert.isFalse(bulk.errors());
  17. Assert.isTrue(2 == bulk.items().size());
  18. //3.批量更新部分数据
  19. Student bulkStudent = new Student();
  20. bulkStudent.setAge(111);
  21. bulk = primaryClient.bulk(b -> b
  22. .index(INDEX_NAME)
  23. .operations(o -> o.update(u -> u.action(a -> a.doc(bulkStudent)).id("1")))
  24. .operations(o -> o.update(u -> u.action(a -> a.doc(bulkStudent)).id("2")))
  25. );
  26. Assert.isFalse(bulk.errors());
  27. Assert.isTrue(2 == bulk.items().size());
  28. //4.查询校验
  29. Student source = primaryClient.get(g -> g
  30. .index(INDEX_NAME)
  31. .id("1"), Student.class
  32. ).source();
  33. Assert.isTrue("{\"name\":\"冯铁城\",\"age\":111}".equals(JSONUtil.toJsonStr(source)));
  34. source = primaryClient.get(g -> g
  35. .index(INDEX_NAME)
  36. .id("2"), Student.class
  37. ).source();
  38. Assert.isTrue("{\"name\":\"张钰玲\",\"age\":111}".equals(JSONUtil.toJsonStr(source)));
  39. //5.批量更新全量数据
  40. Student bulkStudent2 = new Student();
  41. bulk = primaryClient.bulk(b -> b
  42. .index(INDEX_NAME)
  43. .operations(o -> o.index(i -> i.document(bulkStudent2).id("1")))
  44. .operations(o -> o.index(i -> i.document(bulkStudent2).id("2")))
  45. );
  46. Assert.isFalse(bulk.errors());
  47. Assert.isTrue(2 == bulk.items().size());
  48. //6.查询验证
  49. source = primaryClient.get(g -> g
  50. .index(INDEX_NAME)
  51. .id("1"), Student.class
  52. ).source();
  53. Assert.isTrue("{}".equals(JSONUtil.toJsonStr(source)));
  54. source = primaryClient.get(g -> g
  55. .index(INDEX_NAME)
  56. .id("2"), Student.class
  57. ).source();
  58. Assert.isTrue("{}".equals(JSONUtil.toJsonStr(source)));
  59. }

修改文档根据条件

  1. @Test
  2. void updateDocQuery() throws IOException {
  3. //1.准备测试数据
  4. Student student = new Student();
  5. student.setName("冯铁城");
  6. student.setAge(18);
  7. Student studentBak = new Student();
  8. studentBak.setName("张钰玲");
  9. studentBak.setAge(16);
  10. //2.存入测试数据
  11. BulkResponse bulk = primaryClient.bulk(b -> b
  12. .index(INDEX_NAME)
  13. .operations(o -> o.create(c -> c.document(student).id("1")))
  14. .operations(o -> o.create(c -> c.document(studentBak).id("2")))
  15. .refresh(Refresh.True)
  16. );
  17. Assert.isFalse(bulk.errors());
  18. Assert.isTrue(2 == bulk.items().size());
  19. //3.更新名称为冯铁城的数据,将其年龄改为100
  20. UpdateByQueryResponse updateByQueryResponse = primaryClient.updateByQuery(u -> u
  21. .index(INDEX_NAME)
  22. .query(q -> q.match(m -> m
  23. .field("name")
  24. .query(query -> query.stringValue("冯铁城"))
  25. ))
  26. .script(s -> s.inline(i -> i
  27. .source("ctx._source.age=100")
  28. ))
  29. .refresh(true)
  30. );
  31. Assert.isTrue(1 == updateByQueryResponse.updated());
  32. //4.查询校验
  33. Student source = primaryClient.get(g -> g
  34. .index(INDEX_NAME)
  35. .id("1"), Student.class
  36. ).source();
  37. Assert.isTrue(100 == source.getAge());
  38. //5.更新名称为冯铁城的数据,移除age属性
  39. updateByQueryResponse = primaryClient.updateByQuery(u -> u
  40. .index(INDEX_NAME)
  41. .query(q -> q.match(m -> m
  42. .field("name")
  43. .query(query -> query.stringValue("冯铁城"))
  44. ))
  45. .script(s -> s.inline(i -> i
  46. .source("ctx._source.remove('age')")
  47. ))
  48. .refresh(true)
  49. );
  50. Assert.isTrue(1 == updateByQueryResponse.updated());
  51. //6.查询校验
  52. source = primaryClient.get(g -> g
  53. .index(INDEX_NAME)
  54. .id("1"), Student.class
  55. ).source();
  56. Assert.isNull(source.getAge());
  57. }

删除文档单个

  1. @Test
  2. void deleteDocSingle() throws IOException {
  3. //1.验证默认文档存在
  4. BooleanResponse exists = secondaryClient.exists(e -> e.index(INDEX_NAME).id(DEFAULT_ID));
  5. Assert.isTrue(exists.value());
  6. //2.删除文档
  7. DeleteResponse delete = secondaryClient.delete(d -> d
  8. .index(INDEX_NAME)
  9. .id(DEFAULT_ID)
  10. .refresh(Refresh.True)
  11. );
  12. Assert.isTrue("deleted".equals(delete.result().jsonValue().toLowerCase(Locale.ROOT)));
  13. //3.再次验证,文档已不存在
  14. exists = secondaryClient.exists(e -> e.index(INDEX_NAME).id(DEFAULT_ID));
  15. Assert.isFalse(exists.value());
  16. }

删除文档批量

  1. @Test
  2. void deleteDocBulk() throws IOException {
  3. //1.存入测试数据
  4. BulkResponse bulk = primaryClient.bulk(b -> b
  5. .index(INDEX_NAME)
  6. .operations(o -> o.create(c -> c.document(new Student()).id("1")))
  7. .operations(o -> o.create(c -> c.document(new Student()).id("2")))
  8. .refresh(Refresh.True)
  9. );
  10. Assert.isFalse(bulk.errors());
  11. //2.验证文档已存在
  12. BooleanResponse exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("1"));
  13. Assert.isTrue(exists.value());
  14. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("2"));
  15. Assert.isTrue(exists.value());
  16. //3.批量删除
  17. bulk = primaryClient.bulk(b -> b
  18. .index(INDEX_NAME)
  19. .operations(o -> o.delete(d -> d.id("1")))
  20. .operations(o -> o.delete(d -> d.id("2")))
  21. .refresh(Refresh.True)
  22. );
  23. Assert.isFalse(bulk.errors());
  24. Assert.isTrue(2 == bulk.items().size());
  25. //4.验证已不存在
  26. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("1"));
  27. Assert.isFalse(exists.value());
  28. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("2"));
  29. Assert.isFalse(exists.value());
  30. }

删除文档根据条件

  1. @Test
  2. void deleteDocQuery() throws IOException {
  3. //1.准备测试数据
  4. Student student1 = new Student();
  5. student1.setAge(11);
  6. Student student2 = new Student();
  7. student2.setAge(18);
  8. //2.存入测试数据
  9. BulkResponse bulk = primaryClient.bulk(b -> b
  10. .index(INDEX_NAME)
  11. .operations(o -> o.create(c -> c.document(student1).id("1")))
  12. .operations(o -> o.create(c -> c.document(student2).id("2")))
  13. .refresh(Refresh.True)
  14. );
  15. Assert.isFalse(bulk.errors());
  16. //3.校验是否存在
  17. BooleanResponse exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("1"));
  18. Assert.isTrue(exists.value());
  19. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("2"));
  20. Assert.isTrue(exists.value());
  21. //4.删除数据
  22. DeleteByQueryResponse age = primaryClient.deleteByQuery(d -> d
  23. .index(INDEX_NAME)
  24. .query(q -> q.term(t -> t
  25. .field("age")
  26. .value(v -> v.longValue(11))
  27. ))
  28. .refresh(true)
  29. );
  30. Assert.isTrue(1 == age.deleted());
  31. //5.校验是否存在
  32. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("1"));
  33. Assert.isFalse(exists.value());
  34. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("2"));
  35. Assert.isTrue(exists.value());
  36. }

完整版单元测试

  1. import cn.hutool.core.lang.Assert;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import cn.hutool.json.JSONUtil;
  5. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  6. import co.elastic.clients.elasticsearch._types.OpType;
  7. import co.elastic.clients.elasticsearch._types.Refresh;
  8. import co.elastic.clients.elasticsearch._types.Result;
  9. import co.elastic.clients.elasticsearch.core.*;
  10. import co.elastic.clients.elasticsearch.core.mget.MultiGetResponseItem;
  11. import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
  12. import co.elastic.clients.transport.endpoints.BooleanResponse;
  13. import com.ftc.elasticsearchtest.entity.Student;
  14. import org.junit.jupiter.api.BeforeEach;
  15. import org.junit.jupiter.api.Test;
  16. import org.springframework.beans.factory.annotation.Qualifier;
  17. import org.springframework.boot.test.context.SpringBootTest;
  18. import javax.annotation.Resource;
  19. import java.io.IOException;
  20. import java.util.List;
  21. import java.util.Locale;
  22. /**
  23. * @author: 冯铁城 [17615007230@163.com]
  24. * @date: 2022-08-22 11:11:22
  25. * @describe: ElasticSearch文档API单元测试
  26. */
  27. @SpringBootTest
  28. public class ElasticsearchDocTest {
  29. @Resource
  30. @Qualifier("primaryElasticsearchClient")
  31. private ElasticsearchClient primaryClient;
  32. @Resource
  33. @Qualifier("secondaryElasticsearchClient")
  34. private ElasticsearchClient secondaryClient;
  35. /**
  36. * 默认文档ID
  37. */
  38. private static final String DEFAULT_ID = "66";
  39. /**
  40. * 测试Mock索引名称常量
  41. */
  42. private static final String INDEX_NAME = "test_index";
  43. @BeforeEach
  44. void createIndexAndFlushAll() throws IOException {
  45. //1.判定索引是否存在
  46. boolean exist = primaryClient
  47. .indices()
  48. .exists(e -> e.index(INDEX_NAME + "_1"))
  49. .value();
  50. //2.索引不存在创建索引
  51. if (!exist) {
  52. CreateIndexResponse createIndexResponse = primaryClient
  53. .indices()
  54. .create(i -> i
  55. .index(INDEX_NAME + "_1")
  56. .aliases(INDEX_NAME, a -> a)
  57. .mappings(m -> m
  58. .properties("name", p -> p.text(t -> t.analyzer("ik_max_word")))
  59. .properties("age", p -> p.integer(in -> in))
  60. )
  61. .settings(s -> s
  62. .refreshInterval(t -> t.time("1s"))
  63. .numberOfShards("3")
  64. .numberOfReplicas("1")
  65. )
  66. );
  67. Assert.isTrue(Boolean.TRUE.equals(createIndexResponse.acknowledged()));
  68. }
  69. //3.清空索引数据
  70. DeleteByQueryResponse delete = primaryClient.deleteByQuery(d -> d
  71. .index(INDEX_NAME)
  72. .query(q -> q.matchAll(m -> m))
  73. .refresh(true)
  74. );
  75. Assert.isTrue(ObjectUtil.isNotNull(delete.deleted()));
  76. //4.创建最新数据
  77. Student student = new Student();
  78. student.setId(66);
  79. student.setName("宋可心");
  80. student.setAge(18);
  81. //5.存入最新数据
  82. IndexResponse index = primaryClient.index(i -> i
  83. .index(INDEX_NAME)
  84. .document(student)
  85. .id(DEFAULT_ID)
  86. .refresh(Refresh.True)
  87. );
  88. Assert.isTrue("created".equals(index.result().jsonValue().toLowerCase(Locale.ROOT)));
  89. }
  90. @Test
  91. void createDocSingle() throws IOException {
  92. //1.创建学生对象
  93. Student student = new Student();
  94. student.setId(1);
  95. student.setName("冯铁城");
  96. student.setAge(11);
  97. //2.创建单个文档不指定ID
  98. IndexResponse indexResponse = primaryClient.index(i -> i
  99. .index(INDEX_NAME)
  100. .document(student)
  101. );
  102. Result result = indexResponse.result();
  103. Assert.isTrue("created".equals(result.jsonValue().toLowerCase(Locale.ROOT)));
  104. //3.创建单个文档指定ID
  105. indexResponse = primaryClient.index(i -> i
  106. .index(INDEX_NAME)
  107. .document(student)
  108. .id("1")
  109. );
  110. result = indexResponse.result();
  111. Assert.isTrue("created".equals(result.jsonValue().toLowerCase(Locale.ROOT)));
  112. //4.创建单个文档进行ID唯一性控制
  113. String errorMessage = null;
  114. try {
  115. primaryClient.index(i -> i
  116. .index(INDEX_NAME)
  117. .document(student)
  118. .id("1")
  119. .opType(OpType.Create)
  120. );
  121. } catch (Exception e) {
  122. errorMessage = e.getMessage();
  123. }
  124. Assert.isTrue(ObjectUtil.isNotNull(errorMessage));
  125. Assert.isTrue(errorMessage.contains("version_conflict_engine_exception"));
  126. }
  127. @Test
  128. void createDocBulk() throws IOException {
  129. //1.创建学生对象
  130. Student student = new Student();
  131. student.setId(1);
  132. student.setName("张钰玲");
  133. student.setAge(11);
  134. //2.批量保存数据不带ID
  135. BulkResponse bulk = primaryClient.bulk(b -> b
  136. .index(INDEX_NAME)
  137. .operations(o -> o.create(c -> c.document(student)))
  138. .operations(o -> o.create(c -> c.document(student)))
  139. );
  140. Assert.isFalse(bulk.errors());
  141. Assert.isTrue(2 == bulk.items().size());
  142. //3.批量保存数据带ID
  143. bulk = primaryClient.bulk(b -> b
  144. .index(INDEX_NAME)
  145. .operations(o -> o.create(c -> c.document(student).id("1")))
  146. .operations(o -> o.create(c -> c.document(student).id("2")))
  147. );
  148. Assert.isFalse(bulk.errors());
  149. Assert.isTrue(2 == bulk.items().size());
  150. }
  151. @Test
  152. void getDocSingle() throws IOException {
  153. //1.创建学生对象
  154. Student student = new Student();
  155. student.setId(1);
  156. student.setName("冯铁城");
  157. student.setAge(18);
  158. Student studentBak = new Student();
  159. student.setId(2);
  160. student.setName("张钰玲");
  161. student.setAge(16);
  162. //2.批量保存数据
  163. BulkResponse bulk = secondaryClient.bulk(b -> b
  164. .index(INDEX_NAME)
  165. .operations(o -> o.create(c -> c.document(student).id("1")))
  166. .operations(o -> o.create(c -> c.document(studentBak).id("2")))
  167. .refresh(Refresh.True)
  168. );
  169. Assert.isFalse(bulk.errors());
  170. Assert.isTrue(2 == bulk.items().size());
  171. //3.根据ID查询单个数据
  172. Student source = secondaryClient.get(g -> g
  173. .index(INDEX_NAME)
  174. .id("1"), Student.class
  175. ).source();
  176. Assert.isTrue(JSONUtil.toJsonStr(student).equals(JSONUtil.toJsonStr(source)));
  177. //4.按照ID批量查询
  178. List<MultiGetResponseItem<Student>> docs = secondaryClient.mget(m -> m
  179. .index(INDEX_NAME)
  180. .ids("1", "2"), Student.class
  181. ).docs();
  182. Assert.isTrue(2 == docs.size());
  183. Student source1 = docs.get(0).result().source();
  184. Assert.isTrue(JSONUtil.toJsonStr(student).equals(JSONUtil.toJsonStr(source1)));
  185. Student source2 = docs.get(1).result().source();
  186. Assert.isTrue(JSONUtil.toJsonStr(studentBak).equals(JSONUtil.toJsonStr(source2)));
  187. }
  188. @Test
  189. void existDoc() throws IOException {
  190. //1.验证数据存在
  191. BooleanResponse exists = secondaryClient.exists(e -> e
  192. .index(INDEX_NAME)
  193. .id(DEFAULT_ID)
  194. );
  195. Assert.isTrue(exists.value());
  196. //2.验证数据不存在
  197. exists = secondaryClient.exists(e -> e
  198. .index(INDEX_NAME)
  199. .id(DEFAULT_ID + "1")
  200. );
  201. Assert.isFalse(exists.value());
  202. }
  203. @Test
  204. void updateDocSingle() throws IOException {
  205. //1.查询默认数据
  206. Student student = primaryClient.get(g -> g
  207. .index(INDEX_NAME)
  208. .id(DEFAULT_ID), Student.class
  209. ).source();
  210. Assert.isTrue(ObjectUtil.isNotNull(student));
  211. //2.全量更新单个数据(立即refresh,为了单元测试方便)
  212. student.setAge(100);
  213. IndexResponse index = primaryClient.index(i -> i
  214. .index(INDEX_NAME)
  215. .document(student)
  216. .id(DEFAULT_ID)
  217. .refresh(Refresh.True)
  218. );
  219. Assert.isTrue("updated".equals(index.result().jsonValue().toLowerCase(Locale.ROOT)));
  220. //3.查询校验
  221. Integer age = primaryClient.get(g -> g
  222. .index(INDEX_NAME)
  223. .id(DEFAULT_ID), Student.class
  224. ).source().getAge();
  225. Assert.isTrue(100 == age);
  226. //4.全量更新单个数据并进行版本控制(立即refresh,为了单元测试方便)
  227. student.setAge(11);
  228. long primaryTerm = index.primaryTerm();
  229. long seqNo = index.seqNo();
  230. index = primaryClient.index(i -> i
  231. .index(INDEX_NAME)
  232. .document(student)
  233. .id(DEFAULT_ID)
  234. .ifPrimaryTerm(primaryTerm)
  235. .ifSeqNo(seqNo)
  236. .refresh(Refresh.True)
  237. );
  238. Assert.isTrue("updated".equals(index.result().jsonValue().toLowerCase(Locale.ROOT)));
  239. //5.查询校验
  240. age = primaryClient.get(g -> g
  241. .index(INDEX_NAME)
  242. .id(DEFAULT_ID), Student.class
  243. ).source().getAge();
  244. Assert.isTrue(11 == age);
  245. //6.全量更新单个数据并进行版本控制(立即refresh,为了单元测试方便)
  246. String errorMessage = null;
  247. try {
  248. primaryClient.index(i -> i
  249. .index(INDEX_NAME)
  250. .document(student)
  251. .id(INDEX_NAME)
  252. .ifPrimaryTerm((long) 1)
  253. .ifSeqNo((long) 2)
  254. .refresh(Refresh.True)
  255. );
  256. } catch (Exception e) {
  257. errorMessage = e.getMessage();
  258. }
  259. Assert.isTrue(StrUtil.isNotBlank(errorMessage));
  260. Assert.isTrue(errorMessage.contains("version_conflict_engine_exception"));
  261. //7.更新文档部分属性
  262. Student studentBak = new Student();
  263. studentBak.setAge(30);
  264. UpdateResponse<Student> update = primaryClient.update(u -> u
  265. .index(INDEX_NAME)
  266. .id(DEFAULT_ID)
  267. .doc(studentBak)
  268. .refresh(Refresh.True), Student.class
  269. );
  270. Assert.isTrue("updated".equals(update.result().jsonValue().toLowerCase(Locale.ROOT)));
  271. //8.查询校验
  272. Student source = primaryClient.get(g -> g
  273. .index(INDEX_NAME)
  274. .id(DEFAULT_ID), Student.class
  275. ).source();
  276. Assert.isTrue(ObjectUtil.isNotNull(source));
  277. Assert.isTrue(studentBak.getAge() == source.getAge());
  278. Assert.isTrue(student.getName().equals(source.getName()));
  279. }
  280. @Test
  281. void updateDocBulk() throws IOException {
  282. //1.准备测试数据
  283. Student student = new Student();
  284. student.setName("冯铁城");
  285. student.setAge(18);
  286. Student studentBak = new Student();
  287. studentBak.setName("张钰玲");
  288. studentBak.setAge(16);
  289. //2.存入测试数据
  290. BulkResponse bulk = primaryClient.bulk(b -> b
  291. .index(INDEX_NAME)
  292. .operations(o -> o.create(c -> c.document(student).id("1")))
  293. .operations(o -> o.create(c -> c.document(studentBak).id("2")))
  294. );
  295. Assert.isFalse(bulk.errors());
  296. Assert.isTrue(2 == bulk.items().size());
  297. //3.批量更新部分数据
  298. Student bulkStudent = new Student();
  299. bulkStudent.setAge(111);
  300. bulk = primaryClient.bulk(b -> b
  301. .index(INDEX_NAME)
  302. .operations(o -> o.update(u -> u.action(a -> a.doc(bulkStudent)).id("1")))
  303. .operations(o -> o.update(u -> u.action(a -> a.doc(bulkStudent)).id("2")))
  304. );
  305. Assert.isFalse(bulk.errors());
  306. Assert.isTrue(2 == bulk.items().size());
  307. //4.查询校验
  308. Student source = primaryClient.get(g -> g
  309. .index(INDEX_NAME)
  310. .id("1"), Student.class
  311. ).source();
  312. Assert.isTrue("{\"name\":\"冯铁城\",\"age\":111}".equals(JSONUtil.toJsonStr(source)));
  313. source = primaryClient.get(g -> g
  314. .index(INDEX_NAME)
  315. .id("2"), Student.class
  316. ).source();
  317. Assert.isTrue("{\"name\":\"张钰玲\",\"age\":111}".equals(JSONUtil.toJsonStr(source)));
  318. //5.批量更新全量数据
  319. Student bulkStudent2 = new Student();
  320. bulk = primaryClient.bulk(b -> b
  321. .index(INDEX_NAME)
  322. .operations(o -> o.index(i -> i.document(bulkStudent2).id("1")))
  323. .operations(o -> o.index(i -> i.document(bulkStudent2).id("2")))
  324. );
  325. Assert.isFalse(bulk.errors());
  326. Assert.isTrue(2 == bulk.items().size());
  327. //6.查询验证
  328. source = primaryClient.get(g -> g
  329. .index(INDEX_NAME)
  330. .id("1"), Student.class
  331. ).source();
  332. Assert.isTrue("{}".equals(JSONUtil.toJsonStr(source)));
  333. source = primaryClient.get(g -> g
  334. .index(INDEX_NAME)
  335. .id("2"), Student.class
  336. ).source();
  337. Assert.isTrue("{}".equals(JSONUtil.toJsonStr(source)));
  338. }
  339. @Test
  340. void updateDocQuery() throws IOException {
  341. //1.准备测试数据
  342. Student student = new Student();
  343. student.setName("冯铁城");
  344. student.setAge(18);
  345. Student studentBak = new Student();
  346. studentBak.setName("张钰玲");
  347. studentBak.setAge(16);
  348. //2.存入测试数据
  349. BulkResponse bulk = primaryClient.bulk(b -> b
  350. .index(INDEX_NAME)
  351. .operations(o -> o.create(c -> c.document(student).id("1")))
  352. .operations(o -> o.create(c -> c.document(studentBak).id("2")))
  353. .refresh(Refresh.True)
  354. );
  355. Assert.isFalse(bulk.errors());
  356. Assert.isTrue(2 == bulk.items().size());
  357. //3.更新名称为冯铁城的数据,将其年龄改为100
  358. UpdateByQueryResponse updateByQueryResponse = primaryClient.updateByQuery(u -> u
  359. .index(INDEX_NAME)
  360. .query(q -> q.match(m -> m
  361. .field("name")
  362. .query(query -> query.stringValue("冯铁城"))
  363. ))
  364. .script(s -> s.inline(i -> i
  365. .source("ctx._source.age=100")
  366. ))
  367. .refresh(true)
  368. );
  369. Assert.isTrue(1 == updateByQueryResponse.updated());
  370. //4.查询校验
  371. Student source = primaryClient.get(g -> g
  372. .index(INDEX_NAME)
  373. .id("1"), Student.class
  374. ).source();
  375. Assert.isTrue(100 == source.getAge());
  376. //5.更新名称为冯铁城的数据,移除age属性
  377. updateByQueryResponse = primaryClient.updateByQuery(u -> u
  378. .index(INDEX_NAME)
  379. .query(q -> q.match(m -> m
  380. .field("name")
  381. .query(query -> query.stringValue("冯铁城"))
  382. ))
  383. .script(s -> s.inline(i -> i
  384. .source("ctx._source.remove('age')")
  385. ))
  386. .refresh(true)
  387. );
  388. Assert.isTrue(1 == updateByQueryResponse.updated());
  389. //6.查询校验
  390. source = primaryClient.get(g -> g
  391. .index(INDEX_NAME)
  392. .id("1"), Student.class
  393. ).source();
  394. Assert.isNull(source.getAge());
  395. }
  396. @Test
  397. void deleteDocSingle() throws IOException {
  398. //1.验证默认文档存在
  399. BooleanResponse exists = secondaryClient.exists(e -> e.index(INDEX_NAME).id(DEFAULT_ID));
  400. Assert.isTrue(exists.value());
  401. //2.删除文档
  402. DeleteResponse delete = secondaryClient.delete(d -> d
  403. .index(INDEX_NAME)
  404. .id(DEFAULT_ID)
  405. .refresh(Refresh.True)
  406. );
  407. Assert.isTrue("deleted".equals(delete.result().jsonValue().toLowerCase(Locale.ROOT)));
  408. //3.再次验证,文档已不存在
  409. exists = secondaryClient.exists(e -> e.index(INDEX_NAME).id(DEFAULT_ID));
  410. Assert.isFalse(exists.value());
  411. }
  412. @Test
  413. void deleteDocBulk() throws IOException {
  414. //1.存入测试数据
  415. BulkResponse bulk = primaryClient.bulk(b -> b
  416. .index(INDEX_NAME)
  417. .operations(o -> o.create(c -> c.document(new Student()).id("1")))
  418. .operations(o -> o.create(c -> c.document(new Student()).id("2")))
  419. .refresh(Refresh.True)
  420. );
  421. Assert.isFalse(bulk.errors());
  422. //2.验证文档已存在
  423. BooleanResponse exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("1"));
  424. Assert.isTrue(exists.value());
  425. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("2"));
  426. Assert.isTrue(exists.value());
  427. //3.批量删除
  428. bulk = primaryClient.bulk(b -> b
  429. .index(INDEX_NAME)
  430. .operations(o -> o.delete(d -> d.id("1")))
  431. .operations(o -> o.delete(d -> d.id("2")))
  432. .refresh(Refresh.True)
  433. );
  434. Assert.isFalse(bulk.errors());
  435. Assert.isTrue(2 == bulk.items().size());
  436. //4.验证已不存在
  437. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("1"));
  438. Assert.isFalse(exists.value());
  439. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("2"));
  440. Assert.isFalse(exists.value());
  441. }
  442. @Test
  443. void deleteDocQuery() throws IOException {
  444. //1.准备测试数据
  445. Student student1 = new Student();
  446. student1.setAge(11);
  447. Student student2 = new Student();
  448. student2.setAge(18);
  449. //2.存入测试数据
  450. BulkResponse bulk = primaryClient.bulk(b -> b
  451. .index(INDEX_NAME)
  452. .operations(o -> o.create(c -> c.document(student1).id("1")))
  453. .operations(o -> o.create(c -> c.document(student2).id("2")))
  454. .refresh(Refresh.True)
  455. );
  456. Assert.isFalse(bulk.errors());
  457. //3.校验是否存在
  458. BooleanResponse exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("1"));
  459. Assert.isTrue(exists.value());
  460. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("2"));
  461. Assert.isTrue(exists.value());
  462. //4.删除数据
  463. DeleteByQueryResponse age = primaryClient.deleteByQuery(d -> d
  464. .index(INDEX_NAME)
  465. .query(q -> q.term(t -> t
  466. .field("age")
  467. .value(v -> v.longValue(11))
  468. ))
  469. .refresh(true)
  470. );
  471. Assert.isTrue(1 == age.deleted());
  472. //5.校验是否存在
  473. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("1"));
  474. Assert.isFalse(exists.value());
  475. exists = primaryClient.exists(e -> e.index(INDEX_NAME).id("2"));
  476. Assert.isTrue(exists.value());
  477. }
  478. }