Gitee项目地址https://gitee.com/linhong-java/lindaxia-es-7.6.xapi

一、客户端学习

https://www.elastic.co/guide/en/elasticsearch/client/index.html
image.png
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/java-rest-high-getting-started-maven.html

二、新建SpringBoot工程

image.png

2.1.设置编译环境

image.png
image.png

2.2.调整Springboot版本

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.2.5.RELEASE</version>
  5. </parent>

2.3自定义es依赖版本

  1. <properties>
  2. <java.version>1.8</java.version>
  3. <elasticsearch.version>7.6.1</elasticsearch.version>
  4. </properties>

image.png
image.png

三、Java测试类

3.1.es客户端工具类

  1. @Configuration
  2. public class ElasticSearchClientConfig {
  3. /**
  4. * 注入高级客户端
  5. *
  6. * @return RestHighLevelClient
  7. */
  8. @Bean
  9. public RestHighLevelClient restHighLevelClient() {
  10. RestHighLevelClient client = new RestHighLevelClient(
  11. RestClient.builder(
  12. new HttpHost("127.0.0.1", 9200, "http")));
  13. return client;
  14. }
  15. }

3.2.es索引的curd

  1. /**
  2. * 7.6.1高级客户端测试
  3. * @author: lindaxia
  4. * @since : create by in 2021-09-12 18:16
  5. */
  6. @SpringBootTest
  7. class EsIndexApplicationTests {
  8. @Autowired
  9. @Qualifier("restHighLevelClient")
  10. private RestHighLevelClient client;
  11. /**
  12. * 1.索引的创建 PUT lindaxia_index
  13. */
  14. @Test
  15. public void testCreateIndex() throws IOException {
  16. //1.创建索引请求
  17. CreateIndexRequest request = new CreateIndexRequest("lindaxia_index");
  18. //2.客户端执行请求 IndicesClient,请求后获得响应
  19. CreateIndexResponse createIndexResponse = client.indices().create(
  20. request, RequestOptions.DEFAULT);
  21. System.out.println(createIndexResponse);
  22. }
  23. /**
  24. * 2.判断索引是否存在
  25. * @throws IOException
  26. */
  27. @Test
  28. public void testExistIndex() throws IOException {
  29. GetIndexRequest request = new GetIndexRequest("lindaxia_index");
  30. boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
  31. System.out.println(exists);
  32. }
  33. /**
  34. * 删除索引
  35. * @throws IOException
  36. */
  37. @Test
  38. public void testDeteletIndex() throws IOException{
  39. DeleteIndexRequest request = new DeleteIndexRequest("lindaxia_index");
  40. AcknowledgedResponse delete = client.indices().delete(
  41. request, RequestOptions.DEFAULT);
  42. System.out.println(delete.isAcknowledged());
  43. }
  44. }

3.3.es文档的curd

  1. /**
  2. * @author: lindaxia
  3. * @since : create by in 2021-09-12 18:16
  4. */
  5. @SpringBootTest
  6. public class EsDocApplicationTests {
  7. @Autowired
  8. @Qualifier("restHighLevelClient")
  9. private RestHighLevelClient client;
  10. /**
  11. * 测试添加文档
  12. *
  13. * @throws IOException
  14. */
  15. @Test
  16. public void testAddDocument() throws IOException {
  17. // 创建对象
  18. User user = new User("林大侠", 25);
  19. // 创建请求
  20. IndexRequest request = new IndexRequest("lindaxia_index");
  21. // 规则 put /lindaxia_index/_doc/1
  22. request.id("1");
  23. request.timeout(TimeValue.timeValueSeconds(1));
  24. // 将数据放入到请求 json
  25. request.source(JSON.toJSONString(user), XContentType.JSON);
  26. // 客户端发送请求
  27. IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
  28. // IndexResponse[index=lindaxia_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
  29. System.out.println(indexResponse.toString());
  30. // CREATED
  31. System.out.println(indexResponse.status());
  32. }
  33. /**
  34. * 判断文档是否存在 get /index/doc/1
  35. *
  36. * @throws IOException
  37. */
  38. @Test
  39. public void testIsExists() throws IOException {
  40. GetRequest getRequest = new GetRequest("lindaxia_index", "1");
  41. getRequest.fetchSourceContext(new FetchSourceContext(false));
  42. getRequest.storedFields("_none_");
  43. boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
  44. System.out.println(exists);
  45. }
  46. /**
  47. * 获取文档信息
  48. *
  49. * @throws IOException {"age":25,"name":"林大侠"}
  50. * {"_index":"lindaxia_index","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"age":25,"name":"林大侠"}}
  51. */
  52. @Test
  53. public void testGetDocument() throws IOException {
  54. GetRequest getRequest = new GetRequest("lindaxia_index", "1");
  55. GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
  56. // 打印文档的内容
  57. System.out.println(getResponse.getSourceAsString());
  58. System.out.println(getResponse);
  59. }
  60. /**
  61. * 更新文档信息
  62. *
  63. * @throws IOException
  64. */
  65. @Test
  66. public void testUpdateDocument() throws IOException {
  67. UpdateRequest updateRequest = new UpdateRequest("lindaxia_index", "1");
  68. updateRequest.timeout("1s");
  69. User user = new User("林大侠学java", 26);
  70. updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
  71. UpdateResponse updateResponse = client.update(
  72. updateRequest, RequestOptions.DEFAULT);
  73. // OK
  74. System.out.println(updateResponse.status());
  75. }
  76. /**
  77. * 删除文档信息(删除1号用户信息)
  78. *
  79. * @throws IOException
  80. */
  81. @Test
  82. public void testDeleteDocument() throws IOException {
  83. DeleteRequest updateRequest = new DeleteRequest("lindaxia_index", "1");
  84. updateRequest.timeout("1s");
  85. DeleteResponse updateResponse = client.delete(
  86. updateRequest, RequestOptions.DEFAULT);
  87. // OK
  88. System.out.println(updateResponse.status());
  89. }
  90. /**
  91. * 批量插入数据
  92. * 批量更新和批量删除
  93. *
  94. * @throws IOException
  95. */
  96. @Test
  97. public void testBulkDocument() throws IOException {
  98. BulkRequest bulkRequest = new BulkRequest();
  99. bulkRequest.timeout("10s");
  100. ArrayList<User> list = new ArrayList<>();
  101. list.add(new User("林大侠1", 18));
  102. list.add(new User("林大侠2", 19));
  103. list.add(new User("林大侠3", 20));
  104. list.add(new User("林大侠4", 21));
  105. list.add(new User("林大侠5", 22));
  106. for (int i = 0; i < list.size(); i++) {
  107. bulkRequest.add(
  108. new IndexRequest("lindaxia_index")
  109. .id("" + (i + 1))
  110. .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
  111. }
  112. BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
  113. //是否失败 false 则批量插入成功
  114. System.out.println(bulkResponse.hasFailures());
  115. }
  116. /**
  117. * 查询
  118. * 注意:name为中文 这里无法查询到结果
  119. * name类型不是keyword,精确查询不是keyword只能查询单个汉字
  120. *
  121. * SearchSourceBuilder 条件构造
  122. * HighlightBuilder 构建高亮
  123. * TermQueryBuilder 精确查询
  124. *
  125. * @throws IOException
  126. */
  127. @Test
  128. public void testSearch() throws IOException {
  129. SearchRequest searchRequest = new SearchRequest("lindaxia_index");
  130. //构建搜索条件
  131. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  132. //查询条件,可以使用QueryBuilders工具类
  133. //QueryBuilders.termQuery 精确匹配
  134. //name为中文 这里无法查询到结果
  135. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age", "18");
  136. //MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
  137. searchSourceBuilder.query(termQueryBuilder);
  138. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  139. searchRequest.source(searchSourceBuilder);
  140. SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
  141. //{"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":1.0,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"林大侠1","age":18},"sourceAsString":"{\"age\":18,\"name\":\"林大侠1\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":1.0,"totalHits":{"relation":"EQUAL_TO","value":1}}
  142. System.out.println(JSON.toJSONString(searchResponse.getHits()));
  143. System.out.println("===========================================");
  144. SearchHit[] hits = searchResponse.getHits().getHits();
  145. for (SearchHit documentFields : hits) {
  146. //{name=林大侠1, age=18}
  147. System.out.println(documentFields.getSourceAsMap());
  148. }
  149. }
  150. }