1. 文档

官方文档:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/_index_apis.html 找和自己版本、语言相对应的文档

image.pngimage.pngimage.png
Java REST Client 有两种风格:

  • Java Low Level REST Client :用于Elasticsearch的官方低级客户端。它允许通过http与Elasticsearch集群通信。将请求编排和响应反编排留给用户自己处理。它兼容所有的Elasticsearch版本。(PS:学过WebService的话,对编排与反编排这个概念应该不陌生。可以理解为对请求参数的封装,以及对响应结果的解析)

  • Java High Level REST Client :用于Elasticsearch的官方高级客户端。它是基于低级客户端的,它提供很多API,并负责请求的编排与响应的反编排。(PS:就好比是,一个是传自己拼接好的字符串,并且自己解析返回的结果;而另一个是传对象,返回的结果也已经封装好了,直接是对象,更加规范了参数的名称以及格式,更加面对对象一点)

Tip:我们使用 High Level REST Client

2. 使用步骤

2.1 创建 springboot 项目

2.2 配置依赖(改pom)

  1. <properties>
  2. <java.version>1.8</java.version>
  3. <!-- 这里SpringBoot默认配置的版本和使用的es不匹配,我们需要自己配置版本! -->
  4. <elasticsearch.version>7.6.1</elasticsearch.version>
  5. </properties>
  6. <!-- 这里的依赖可用去maven仓库寻找 -->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  10. </dependency>

2.3 自定义config

  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.client.RestClient;
  3. import org.elasticsearch.client.RestHighLevelClient;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. public class EsConfig {
  8. @Bean
  9. RestHighLevelClient restHighLevelClient() {
  10. return new RestHighLevelClient(
  11. // 配置ip和端口
  12. RestClient.builder(
  13. new HttpHost("localhost", 9201, "http"), // 构建客户端对象
  14. new HttpHost("localhost", 9200)));
  15. }
  16. }

2.4 测试代码

  1. package com.edward;
  2. import com.alibaba.fastjson.JSON;
  3. import com.edward.entity.User;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  6. import org.elasticsearch.action.bulk.BulkRequest;
  7. import org.elasticsearch.action.bulk.BulkResponse;
  8. import org.elasticsearch.action.delete.DeleteRequest;
  9. import org.elasticsearch.action.delete.DeleteResponse;
  10. import org.elasticsearch.action.get.GetRequest;
  11. import org.elasticsearch.action.get.GetResponse;
  12. import org.elasticsearch.action.index.IndexRequest;
  13. import org.elasticsearch.action.index.IndexResponse;
  14. import org.elasticsearch.action.search.SearchRequest;
  15. import org.elasticsearch.action.search.SearchResponse;
  16. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  17. import org.elasticsearch.action.update.UpdateRequest;
  18. import org.elasticsearch.action.update.UpdateResponse;
  19. import org.elasticsearch.client.RequestOptions;
  20. import org.elasticsearch.client.RestHighLevelClient;
  21. import org.elasticsearch.client.indices.CreateIndexRequest;
  22. import org.elasticsearch.client.indices.CreateIndexResponse;
  23. import org.elasticsearch.client.indices.GetIndexRequest;
  24. import org.elasticsearch.client.indices.GetIndexResponse;
  25. import org.elasticsearch.common.xcontent.XContentType;
  26. import org.elasticsearch.index.query.QueryBuilder;
  27. import org.elasticsearch.index.query.QueryBuilders;
  28. import org.elasticsearch.rest.RestStatus;
  29. import org.elasticsearch.search.SearchHit;
  30. import org.elasticsearch.search.builder.SearchSourceBuilder;
  31. import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
  32. import org.junit.jupiter.api.Test;
  33. import org.springframework.beans.factory.annotation.Autowired;
  34. import org.springframework.beans.factory.annotation.Qualifier;
  35. import org.springframework.boot.test.context.SpringBootTest;
  36. import java.io.IOException;
  37. import java.util.ArrayList;
  38. @Slf4j
  39. @SpringBootTest
  40. class EsDemoApplicationTests {
  41. @Autowired
  42. private RestHighLevelClient restHighLevelClient;
  43. /*
  44. *-------------------------索引--------------------------
  45. * 创建索引
  46. * */
  47. @Test
  48. void testCreateIndices() throws IOException {
  49. CreateIndexRequest request = new CreateIndexRequest("es_index_demo");
  50. CreateIndexResponse response = restHighLevelClient.
  51. indices().create(request, RequestOptions.DEFAULT);
  52. log.info("create index result:{}", response.isAcknowledged()); // true(成功) | 失败抛异常
  53. }
  54. /*
  55. * 测试索引是否存在
  56. * */
  57. @Test
  58. void testExistIndices() throws IOException {
  59. GetIndexRequest request = new GetIndexRequest("es_index_demo");
  60. boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
  61. log.info("res:{}", exists); // true(存在) | false(不存在)
  62. }
  63. /*
  64. * 测试删除索引
  65. * */
  66. @Test
  67. void testDeleteIndices() throws IOException {
  68. DeleteIndexRequest request = new DeleteIndexRequest("es_index_demo");
  69. AcknowledgedResponse response = restHighLevelClient.
  70. indices().delete(request, RequestOptions.DEFAULT);
  71. log.info("deleteRes:{}", response.isAcknowledged()); // true(删除成功,若无这个索引也返回true)
  72. }
  73. /*
  74. *-------------------------文档--------------------------
  75. * 测试添加文档
  76. * */
  77. @Test
  78. void testAddDocument() throws IOException {
  79. User user = User.builder().name("大龙").age(20).build();
  80. IndexRequest request = new IndexRequest("es_index_demo")
  81. .id("1") // id 不指定则生成随机字符串
  82. .source(JSON.toJSONString(user), XContentType.JSON);
  83. // 发送请求
  84. IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
  85. log.info("status:{}",response.status()); // CREATED(没这条文档,初次创建) | OK(更新)
  86. log.info("getResult:{}",response.getResult()); // CREATED(没这条文档,初次创建) | UPDATED(更新)
  87. }
  88. /*
  89. * 测试文档是否存在(根据索引和文档id判断)
  90. * */
  91. @Test
  92. void testExistDocument() throws IOException {
  93. GetRequest request = new GetRequest("es_index_demo","1");
  94. // 不获取 _source 上下文
  95. request.fetchSourceContext(new FetchSourceContext(false));
  96. // 不获取 stored fields
  97. request.storedFields("_none_");
  98. // 判断是否存在
  99. boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
  100. log.info("exist:{}", exists); // true(存在) | false(不存在)
  101. }
  102. /*
  103. * 测试更新某个文档(根据文档id)
  104. * */
  105. @Test
  106. void testUpdateDocument() throws IOException {
  107. User user = User.builder().name("小龙").age(1).build();
  108. // 构建请求信息
  109. UpdateRequest request = new UpdateRequest("es_index_demo", "1");
  110. request.doc(JSON.toJSONString(user), XContentType.JSON);
  111. // 发送更新请求
  112. UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
  113. log.info("res:{}", response);
  114. log.info("res - status:{}", response.status()); // OK(成功)
  115. }
  116. /*
  117. * 测试删除某个文档(根据文档id)
  118. * */
  119. @Test
  120. void testDeleteDocument() throws IOException {
  121. DeleteRequest request = new DeleteRequest("es_index_demo", "1");
  122. DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
  123. log.info("response:{}",response.status()); // OK(删除成功) | NOT_FOUND(未找到)
  124. log.info("RestStatus.OK,{}", RestStatus.OK); // OK
  125. }
  126. /*
  127. * 测试根据索引和文档id获取文档信息
  128. * */
  129. @Test
  130. void testGetDocument() throws IOException {
  131. GetRequest request = new GetRequest("es_index_demo", "1");
  132. GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
  133. log.info("result_source_String:{}",response.getSourceAsString()); // 获取 _source 的内容并转为字符串 | 没数据返回null
  134. log.info("result_source_Map:{}",response.getSourceAsMap()); // 获取 _source 的内容并转为map | 没数据返回 null
  135. }
  136. /*
  137. * 批量添加文档
  138. * */
  139. @Test
  140. void testBulkDocument() throws IOException {
  141. ArrayList<User> userList = new ArrayList<>();
  142. userList.add(new User("edward1",3));
  143. userList.add(new User("edward2",3));
  144. userList.add(new User("edward3",3));
  145. userList.add(new User("damon1",3));
  146. userList.add(new User("damon2",3));
  147. userList.add(new User("damon3",3));
  148. // 构建请求数据
  149. BulkRequest bulkRequest = new BulkRequest();
  150. for (User user : userList) {
  151. bulkRequest.add(new IndexRequest("es_index_demo")
  152. .source(JSON.toJSONString(user), XContentType.JSON));
  153. }
  154. // 发送请求
  155. BulkResponse response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
  156. log.info("response-status,{}", response.status()); // OK
  157. log.info("response-hasFailures,{}", response.hasFailures()); // false
  158. }
  159. /*
  160. * 查询测试
  161. * */
  162. @Test
  163. void testSearch() throws IOException {
  164. SearchRequest request = new SearchRequest("es_index_demo");
  165. // 构件查询信息
  166. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  167. searchSourceBuilder.query(QueryBuilders.matchQuery("name", "edward1"));
  168. // 将查询信息放入 request 中
  169. request.source(searchSourceBuilder);
  170. // 发送请求
  171. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
  172. log.info("res_hits:{}",response.getHits());
  173. // 遍历结果集
  174. for (SearchHit hit : response.getHits().getHits()) {
  175. log.info("hit:{}",hit.getSourceAsMap()); // {name=edward1, age=3}
  176. }
  177. }
  178. }

3. es 工具类封装

  1. import com.alibaba.fastjson.JSON;
  2. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  3. import org.elasticsearch.action.bulk.BulkRequest;
  4. import org.elasticsearch.action.bulk.BulkResponse;
  5. import org.elasticsearch.action.delete.DeleteRequest;
  6. import org.elasticsearch.action.delete.DeleteResponse;
  7. import org.elasticsearch.action.get.GetRequest;
  8. import org.elasticsearch.action.get.GetResponse;
  9. import org.elasticsearch.action.index.IndexRequest;
  10. import org.elasticsearch.action.index.IndexResponse;
  11. import org.elasticsearch.action.search.SearchRequest;
  12. import org.elasticsearch.action.search.SearchResponse;
  13. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  14. import org.elasticsearch.action.update.UpdateRequest;
  15. import org.elasticsearch.action.update.UpdateResponse;
  16. import org.elasticsearch.client.RequestOptions;
  17. import org.elasticsearch.client.RestHighLevelClient;
  18. import org.elasticsearch.client.indices.CreateIndexRequest;
  19. import org.elasticsearch.client.indices.CreateIndexResponse;
  20. import org.elasticsearch.client.indices.GetIndexRequest;
  21. import org.elasticsearch.common.unit.TimeValue;
  22. import org.elasticsearch.common.xcontent.XContentType;
  23. import org.elasticsearch.index.query.QueryBuilders;
  24. import org.elasticsearch.rest.RestStatus;
  25. import org.elasticsearch.search.builder.SearchSourceBuilder;
  26. import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
  27. import org.springframework.beans.factory.annotation.Autowired;
  28. import org.springframework.beans.factory.annotation.Qualifier;
  29. import org.springframework.stereotype.Component;
  30. import java.io.IOException;
  31. import java.util.List;
  32. import java.util.concurrent.TimeUnit;
  33. @Component
  34. public class EsUtils<T> {
  35. @Autowired
  36. @Qualifier("restHighLevelClient")
  37. private RestHighLevelClient client;
  38. /**
  39. * 判断索引是否存在
  40. * @param index
  41. * @return
  42. * @throws IOException
  43. */
  44. public boolean existsIndex(String index) throws IOException {
  45. GetIndexRequest request = new GetIndexRequest(index);
  46. boolean exists = client.indices().exists(request,
  47. RequestOptions.DEFAULT);
  48. return exists;
  49. }
  50. /**
  51. * 创建索引
  52. * @param index
  53. * @throws IOException
  54. */
  55. public boolean createIndex(String index) throws IOException {
  56. CreateIndexRequest request = new CreateIndexRequest(index);
  57. CreateIndexResponse createIndexResponse=client.indices()
  58. .create(request,RequestOptions.DEFAULT);
  59. return createIndexResponse.isAcknowledged();
  60. }
  61. /**
  62. * 删除索引
  63. * @param index
  64. * @return
  65. * @throws IOException
  66. */
  67. public boolean deleteIndex(String index) throws IOException {
  68. DeleteIndexRequest deleteIndexRequest = new
  69. DeleteIndexRequest(index);
  70. AcknowledgedResponse response =client.indices()
  71. .delete(deleteIndexRequest, RequestOptions.DEFAULT);
  72. return response.isAcknowledged();
  73. }
  74. /**
  75. * 判断某索引下文档id是否存在
  76. * @param index
  77. * @param id
  78. * @return
  79. * @throws IOException
  80. */
  81. public boolean docExists(String index, String id) throws IOException {
  82. GetRequest getRequest = new GetRequest(index,id);
  83. // 只判断索引是否存在不需要获取_source
  84. getRequest.fetchSourceContext(new FetchSourceContext(false));
  85. getRequest.storedFields("_none_");
  86. boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
  87. return exists;
  88. }
  89. /**
  90. * 添加文档记录
  91. * @param index
  92. * @param id
  93. * @param t 要添加的数据实体类
  94. * @return
  95. * @throws IOException
  96. */
  97. public boolean addDoc(String index,String id,T t) throws IOException {
  98. IndexRequest request = new IndexRequest(index);
  99. request.id(id);
  100. //timeout
  101. request.timeout(TimeValue.timeValueSeconds(1));
  102. request.timeout("1s");
  103. request.source(JSON.toJSONString(t), XContentType.JSON);
  104. IndexResponse indexResponse = client.index(request,RequestOptions.DEFAULT);
  105. RestStatus Status = indexResponse.status();
  106. return Status==RestStatus.OK||Status== RestStatus.CREATED;
  107. }
  108. /**
  109. * 根据id来获取记录
  110. * @param index
  111. * @param id
  112. * @return
  113. * @throws IOException
  114. */
  115. public GetResponse getDoc(String index, String id) throws IOException {
  116. GetRequest request = new GetRequest(index,id);
  117. GetResponse getResponse = client.get(request,RequestOptions.DEFAULT);
  118. return getResponse;
  119. }
  120. /**
  121. * 批量添加文档记录
  122. * 没有设置id ES会自动生成一个,如果要设置 IndexRequest的对象.id()即可
  123. * @param index
  124. * @param list
  125. * @return
  126. * @throws IOException
  127. */
  128. public boolean bulkAdd(String index, List<T> list) throws IOException {
  129. BulkRequest bulkRequest = new BulkRequest();
  130. //timeout
  131. bulkRequest.timeout(TimeValue.timeValueMinutes(2));
  132. bulkRequest.timeout("2m");
  133. for (int i =0;i<list.size();i++){
  134. bulkRequest.add(new IndexRequest(index)
  135. .source(JSON.toJSONString(list.get(i))));
  136. }
  137. BulkResponse bulkResponse = client.bulk(bulkRequest,RequestOptions.DEFAULT);
  138. return !bulkResponse.hasFailures();
  139. }
  140. /**
  141. * 批量删除和更新就不写了可根据上面几个方法来写
  142. */
  143. /**
  144. * 更新文档记录
  145. * @param index
  146. * @param id
  147. * @param t
  148. * @return
  149. * @throws IOException
  150. */
  151. public boolean updateDoc(String index,String id,T t) throws IOException{
  152. UpdateRequest request = new UpdateRequest(index,id);
  153. request.doc(JSON.toJSONString(t));
  154. request.timeout(TimeValue.timeValueSeconds(1));
  155. request.timeout("1s");
  156. UpdateResponse updateResponse = client.update(
  157. request, RequestOptions.DEFAULT);
  158. return updateResponse.status()==RestStatus.OK;
  159. }
  160. /**
  161. * 删除文档记录
  162. * @param index
  163. * @param id
  164. * @return
  165. * @throws IOException
  166. */
  167. public boolean deleteDoc(String index,String id) throws IOException {
  168. DeleteRequest request = new DeleteRequest(index,id);
  169. //timeout
  170. request.timeout(TimeValue.timeValueSeconds(1));
  171. request.timeout("1s");
  172. DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT);
  173. return deleteResponse.status()== RestStatus.OK;
  174. }
  175. /**
  176. * 根据某字段来搜索
  177. * @param index
  178. * @param field
  179. * @param key 要收搜的关键字
  180. * @throws IOException
  181. */
  182. public void search(String index,String field ,String key,Integer from,Integer size) throws IOException {
  183. SearchRequest searchRequest = new SearchRequest(index);
  184. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  185. sourceBuilder.query(QueryBuilders.termQuery(field, key));
  186. //控制搜素
  187. sourceBuilder.from(from);
  188. sourceBuilder.size(size);
  189. //最大搜索时间。
  190. sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  191. searchRequest.source(sourceBuilder);
  192. SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
  193. System.out.println(JSON.toJSONString(searchResponse.getHits()));
  194. }
  195. }