当前位置:   article > 正文

【Elasticsearch学习笔记五】es常用的JAVA API、es整合SpringBoot项目中使用、利用JAVA代码操作es、RestHighLevelClient客户端对象_es java api sortoptions

es java api sortoptions

目录

一、Maven项目集成Easticsearch

1)客户端对象

2)索引操作

3)文档操作

4)高级查询

二、springboot项目集成Spring Data操作Elasticsearch

1)pom文件

2)yaml

3)数据实体类

4)配置类

5)Dao数据访问对象

6)索引操作

7)文档操作

8)文档搜索

三、springboot项目集成bboss操作elasticsearch

1)pom文件和配置

2)getConfigRestClientUtil和getRestClientUtil区别

3)创建索引

4)删除索引

5)判断索引是否存在

6)判断索引类型是否存在

7)添加单个文档

8)批量添加文档

9)查询单个文档


一、Maven项目集成Easticsearch

        Elasticsearch软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对 Elasticsearch服务进行访问。  修改pom 文件,增加 Maven 依赖关系。

  1. <properties>
  2. <java.version>1.8</java.version>
  3. <elasticsearch.version>7.4.2</elasticsearch.version>
  4. </properties>
  5. <dependency>
  6. <groupId>org.elasticsearch.client</groupId>
  7. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  8. <version>7.4.2</version>
  9. </dependency>

1)客户端对象

        创建类,代码中创建 Elasticsearch 客户端对象因为早期版本的客户端对象已经不再推荐使用,且在未来版本中会被删除,所以这里我们采用高级 REST 客户端对象;

  1. public static void main(String[] args) throws IOException {
  2. // 创建客户端对象
  3. RestHighLevelClient client = new RestHighLevelClient(
  4. RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
  5. );
  6. // 关闭客户端连接
  7. client.close();
  8. }

2)索引操作

        ES服务器正常启动后,可以通过 Java API 客户端对象对 ES 索引进行操作 ;

  1. public class EsIndex {
  2. public static void main(String[] args) throws IOException {
  3. // 创建客户端对象
  4. RestHighLevelClient client = new RestHighLevelClient(
  5. RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
  6. );
  7. // 关闭客户端连接
  8. client.close();
  9. }
  10. // 创建索引
  11. public static void createIndex(RestHighLevelClient client) throws IOException {
  12. // 创建索引 - 请求对象
  13. CreateIndexRequest request = new CreateIndexRequest("user");
  14. // 发送请求,获取响应
  15. CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
  16. boolean acknowledged = response.isAcknowledged();
  17. // 响应状态
  18. System.out.println("操作状态 = " + acknowledged);
  19. }
  20. // 查看索引
  21. public static void getIndex(RestHighLevelClient client) throws IOException {
  22. // 查询索引 - 请求对象
  23. GetIndexRequest request = new GetIndexRequest("user");
  24. // 发送请求,获取响应
  25. GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
  26. System.out.println("aliases: " + response.getAliases());
  27. System.out.println("mappings: " + response.getMappings());
  28. System.out.println("settings: " + response.getSettings());
  29. }
  30. // 删除索引
  31. public static void deleteIndex(RestHighLevelClient client) throws IOException {
  32. // 删除索引 - 请求对象
  33. DeleteIndexRequest request = new DeleteIndexRequest("user");
  34. // 发送请求,获取响应
  35. AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
  36. // 操作结果
  37. System.out.println("操作结果: " + response.isAcknowledged());
  38. }
  39. }

3)文档操作

  1. public class EsDoc {
  2. public static void main(String[] args) throws IOException {
  3. // 创建客户端对象
  4. RestHighLevelClient client = new RestHighLevelClient(
  5. RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
  6. );
  7. // 关闭客户端连接
  8. client.close();
  9. }
  10. // 创建文档
  11. public static void createDoc(RestHighLevelClient client) throws IOException {
  12. // 新增文档 - 请求对象
  13. IndexRequest request = new IndexRequest();
  14. // 设置索引及唯一性标识
  15. request.index("user").id("1001");
  16. // 创建数据对象
  17. User user = new User();
  18. user.setAge(26);
  19. user.setSex("男");
  20. user.setName("jak");
  21. ObjectMapper objectMapper = new ObjectMapper();
  22. String productJson = objectMapper.writeValueAsString(user);
  23. // 添加文档数据, 数据格式为Json格式
  24. request.source(productJson, XContentType.JSON);
  25. // 客户端发送请求,获取响应对象
  26. IndexResponse response = client.index(request, RequestOptions.DEFAULT);
  27. // 打印结果信息
  28. System.out.println("_index: " + response.getIndex());
  29. System.out.println("id: " + response.getId());
  30. System.out.println("_result: " + response.getResult());
  31. }
  32. // 修改文档
  33. public static void updateDoc(RestHighLevelClient client) throws IOException {
  34. // 修改文档 - 请求对象
  35. UpdateRequest request = new UpdateRequest();
  36. // 配置修改参数
  37. request.index("user").id("1001");
  38. // 设置请求体,对数据进行修改
  39. request.doc(XContentType.JSON, "sex", "女");
  40. // 客户端发送请求,获取响应对象
  41. UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
  42. System.out.println("_index: " + response.getIndex());
  43. System.out.println("_id: " + response.getId());
  44. System.out.println("_result: " + response.getResult());
  45. }
  46. // 查询文档
  47. public static void getDoc(RestHighLevelClient client) throws IOException {
  48. // 创建请求对象
  49. GetRequest request = new GetRequest().index("user").id("1001");
  50. // 客户端发送请求,获取响应对象
  51. GetResponse response = client.get(request, RequestOptions.DEFAULT);
  52. // 打印结果信息
  53. System.out.println("_index: " + response.getIndex());
  54. System.out.println("_type: " + response.getType());
  55. System.out.println("_id: " + response.getId());
  56. System.out.println("source: " + response.getSourceAsString());
  57. }
  58. // 删除文档
  59. public static void deleteDoc(RestHighLevelClient client) throws IOException {
  60. // 创建请求对象
  61. DeleteRequest request = new DeleteRequest().index("user").id("1");
  62. // 客户端发送请求,获取响应对象
  63. DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
  64. // 打印信息
  65. System.out.println(response.toString());
  66. }
  67. // 批量新增
  68. public static void bulkCreateDoc(RestHighLevelClient client) throws IOException {
  69. // 创建批量新增请求对象
  70. BulkRequest request = new BulkRequest();
  71. request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan"));
  72. request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi"));
  73. request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu"));
  74. // 客户端发送请求,获取响应对象
  75. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  76. // 打印结果信息
  77. System.out.println("took: " + responses.getTook());
  78. System.out.println("items: " + Arrays.toString(responses.getItems()));
  79. }
  80. // 批量删除
  81. public static void bulkDeleteDoc(RestHighLevelClient client) throws IOException {
  82. // 创建批量删除请求对象
  83. BulkRequest request = new BulkRequest();
  84. request.add(new DeleteRequest().index("user").id("1001"));
  85. request.add(new DeleteRequest().index("user").id("1002"));
  86. request.add(new DeleteRequest().index("user").id("1003"));
  87. // 客户端发送请求,获取响应对象
  88. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  89. // 打印结果信息
  90. System.out.println("took: " + responses.getTook());
  91. System.out.println("items: " + Arrays.toString(responses.getItems()));
  92. }
  93. }

4)高级查询

  1. public class EsSearch {
  2. public static void main(String[] args) throws IOException {
  3. // 创建客户端对象
  4. RestHighLevelClient client = new RestHighLevelClient(
  5. RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
  6. );
  7. // 关闭客户端连接
  8. client.close();
  9. }
  10. // 查询所有索引数据
  11. public static void matchAllQuery(RestHighLevelClient client) throws IOException {
  12. // 创建搜索请求对象
  13. SearchRequest request = new SearchRequest();
  14. request.indices("student");
  15. // 构建查询的请求体
  16. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  17. // 查询所有数据
  18. sourceBuilder.query(QueryBuilders.matchAllQuery());
  19. request.source(sourceBuilder);
  20. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  21. // 查询匹配
  22. SearchHits hits = response.getHits();
  23. System.out.println("took: " + response.getTook());
  24. System.out.println("timeout: " + response.isTimedOut());
  25. System.out.println("total: " + hits.getTotalHits());
  26. System.out.println("MaxScore: " + hits.getMaxScore());
  27. System.out.println("hits------------->");
  28. for (SearchHit hit : hits) {
  29. // 输出每条查询的结果信息
  30. System.out.println(hit.getSourceAsString());
  31. }
  32. System.out.println("<-----------------");
  33. }
  34. // term查询,查询条件为关键字
  35. public static void termQuery(RestHighLevelClient client) throws IOException {
  36. // 创建搜索请求对象
  37. SearchRequest request = new SearchRequest();
  38. request.indices("student");
  39. // 构建查询的请求体
  40. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  41. // 查询所有数据
  42. sourceBuilder.query(QueryBuilders.termQuery("age", "30"));
  43. request.source(sourceBuilder);
  44. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  45. // 查询匹配
  46. SearchHits hits = response.getHits();
  47. System.out.println("took: " + response.getTook());
  48. System.out.println("timeout: " + response.isTimedOut());
  49. System.out.println("total: " + hits.getTotalHits());
  50. System.out.println("MaxScore: " + hits.getMaxScore());
  51. System.out.println("hits------------->");
  52. for (SearchHit hit : hits) {
  53. // 输出每条查询的结果信息
  54. System.out.println(hit.getSourceAsString());
  55. }
  56. System.out.println("<-----------------");
  57. }
  58. // 分页查询
  59. public static void pageQuery(RestHighLevelClient client) throws IOException {
  60. // 创建搜索请求对象
  61. SearchRequest request = new SearchRequest();
  62. request.indices("student");
  63. // 构建查询的请求体
  64. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  65. // 查询所有数据
  66. sourceBuilder.query(QueryBuilders.matchAllQuery());
  67. // 分页查询
  68. // 当前页起始索引(第一条数据的顺序号),from
  69. sourceBuilder.from(0);
  70. // 每页显示多少条size
  71. sourceBuilder.size(2);
  72. request.source(sourceBuilder);
  73. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  74. // 查询匹配
  75. SearchHits hits = response.getHits();
  76. System.out.println("took: " + response.getTook());
  77. System.out.println("timeout: " + response.isTimedOut());
  78. System.out.println("total: " + hits.getTotalHits());
  79. System.out.println("MaxScore: " + hits.getMaxScore());
  80. System.out.println("hits------------->");
  81. for (SearchHit hit : hits) {
  82. // 输出每条查询的结果信息
  83. System.out.println(hit.getSourceAsString());
  84. }
  85. System.out.println("<-----------------");
  86. }
  87. // 数据排序
  88. public static void sortOrderQuery(RestHighLevelClient client) throws IOException {
  89. // 创建搜索请求对象
  90. SearchRequest request = new SearchRequest();
  91. request.indices("student");
  92. // 构建查询的请求体
  93. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  94. // 查询所有数据
  95. sourceBuilder.query(QueryBuilders.matchAllQuery());
  96. // 排序
  97. sourceBuilder.sort("age", SortOrder.ASC);
  98. request.source(sourceBuilder);
  99. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  100. // 查询匹配
  101. SearchHits hits = response.getHits();
  102. System.out.println("took: " + response.getTook());
  103. System.out.println("timeout: " + response.isTimedOut());
  104. System.out.println("total: " + hits.getTotalHits());
  105. System.out.println("MaxScore: " + hits.getMaxScore());
  106. System.out.println("hits------------->");
  107. for (SearchHit hit : hits) {
  108. // 输出每条查询的结果信息
  109. System.out.println(hit.getSourceAsString());
  110. }
  111. System.out.println("<-----------------");
  112. }
  113. // 过滤字段
  114. public static void filterFieldsQuery(RestHighLevelClient client) throws IOException {
  115. // 创建搜索请求对象
  116. SearchRequest request = new SearchRequest();
  117. request.indices("student");
  118. // 构建查询的请求体
  119. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  120. // 查询所有数据
  121. sourceBuilder.query(QueryBuilders.matchAllQuery());
  122. // 查询字段过滤
  123. String[] excludes = {};
  124. String[] includes = {"name", "age"};
  125. sourceBuilder.fetchSource(includes, excludes);
  126. request.source(sourceBuilder);
  127. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  128. // 查询匹配
  129. SearchHits hits = response.getHits();
  130. System.out.println("took: " + response.getTook());
  131. System.out.println("timeout: " + response.isTimedOut());
  132. System.out.println("total: " + hits.getTotalHits());
  133. System.out.println("MaxScore: " + hits.getMaxScore());
  134. System.out.println("hits------------->");
  135. for (SearchHit hit : hits) {
  136. // 输出每条查询的结果信息
  137. System.out.println(hit.getSourceAsString());
  138. }
  139. System.out.println("<-----------------");
  140. }
  141. // Bool查询
  142. public static void boolQuery(RestHighLevelClient client) throws IOException {
  143. // 创建搜索请求对象
  144. SearchRequest request = new SearchRequest();
  145. request.indices("student");
  146. // 构建查询的请求体
  147. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  148. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  149. // 必须包含
  150. boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
  151. // 一定不含
  152. boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
  153. // 可能包含
  154. boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
  155. // 查询所有数据
  156. sourceBuilder.query(boolQueryBuilder);
  157. request.source(sourceBuilder);
  158. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  159. // 查询匹配
  160. SearchHits hits = response.getHits();
  161. System.out.println("took: " + response.getTook());
  162. System.out.println("timeout: " + response.isTimedOut());
  163. System.out.println("total: " + hits.getTotalHits());
  164. System.out.println("MaxScore: " + hits.getMaxScore());
  165. System.out.println("hits------------->");
  166. for (SearchHit hit : hits) {
  167. // 输出每条查询的结果信息
  168. System.out.println(hit.getSourceAsString());
  169. }
  170. System.out.println("<-----------------");
  171. }
  172. // 范围查询
  173. public static void rangeQuery(RestHighLevelClient client) throws IOException {
  174. // 创建搜索请求对象
  175. SearchRequest request = new SearchRequest();
  176. request.indices("student");
  177. // 构建查询的请求体
  178. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  179. RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
  180. // 大于等于
  181. rangeQuery.gte("30");
  182. // 小于等于
  183. rangeQuery.lte("40");
  184. // 查询所有数据
  185. sourceBuilder.query(rangeQuery);
  186. request.source(sourceBuilder);
  187. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  188. // 查询匹配
  189. SearchHits hits = response.getHits();
  190. System.out.println("took: " + response.getTook());
  191. System.out.println("timeout: " + response.isTimedOut());
  192. System.out.println("total: " + hits.getTotalHits());
  193. System.out.println("MaxScore: " + hits.getMaxScore());
  194. System.out.println("hits------------->");
  195. for (SearchHit hit : hits) {
  196. // 输出每条查询的结果信息
  197. System.out.println(hit.getSourceAsString());
  198. }
  199. System.out.println("<-----------------");
  200. }
  201. // 范围查询
  202. public static void fuzzyQuery(RestHighLevelClient client) throws IOException {
  203. // 创建搜索请求对象
  204. SearchRequest request = new SearchRequest();
  205. request.indices("student");
  206. // 构建查询的请求体
  207. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  208. // 查询所有数据
  209. sourceBuilder.query(QueryBuilders.fuzzyQuery("name", "zhangsan").fuzziness(Fuzziness.ONE));
  210. request.source(sourceBuilder);
  211. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  212. // 查询匹配
  213. SearchHits hits = response.getHits();
  214. System.out.println("took: " + response.getTook());
  215. System.out.println("timeout: " + response.isTimedOut());
  216. System.out.println("total: " + hits.getTotalHits());
  217. System.out.println("MaxScore: " + hits.getMaxScore());
  218. System.out.println("hits------------->");
  219. for (SearchHit hit : hits) {
  220. // 输出每条查询的结果信息
  221. System.out.println(hit.getSourceAsString());
  222. }
  223. System.out.println("<-----------------");
  224. }
  225. // 高亮查询
  226. public static void highLightQuery(RestHighLevelClient client) throws IOException {
  227. // 创建搜索请求对象
  228. SearchRequest request = new SearchRequest();
  229. request.indices("student");
  230. // 构建查询的请求体
  231. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  232. // 构建查询方式: 高亮查询
  233. TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "zhangsan");
  234. // 设置查询方式
  235. sourceBuilder.query(termsQueryBuilder);
  236. // 构建高亮字段
  237. HighlightBuilder highlightBuilder = new HighlightBuilder();
  238. // 设置标签前缀
  239. highlightBuilder.preTags("<font color='red'>");
  240. // 设置标签后缀
  241. highlightBuilder.postTags("</font>");
  242. // 设置高亮字段
  243. highlightBuilder.field("name");
  244. // 设置高亮构建对象
  245. sourceBuilder.highlighter(highlightBuilder);
  246. // 设置请求体
  247. request.source(sourceBuilder);
  248. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  249. // 查询匹配
  250. SearchHits hits = response.getHits();
  251. System.out.println("took: " + response.getTook());
  252. System.out.println("timeout: " + response.isTimedOut());
  253. System.out.println("total: " + hits.getTotalHits());
  254. System.out.println("MaxScore: " + hits.getMaxScore());
  255. System.out.println("hits------------->");
  256. for (SearchHit hit : hits) {
  257. // 输出每条查询的结果信息
  258. System.out.println(hit.getSourceAsString());
  259. }
  260. System.out.println("<-----------------");
  261. }
  262. // 聚合查询
  263. public static void AggrQuery(RestHighLevelClient client) throws IOException {
  264. // 创建搜索请求对象
  265. SearchRequest request = new SearchRequest();
  266. request.indices("student");
  267. // 构建查询的请求体
  268. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  269. sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
  270. // 设置请求体
  271. request.source(sourceBuilder);
  272. // 客户端发送请求,获取响应对象
  273. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  274. // 查询匹配
  275. SearchHits hits = response.getHits();
  276. System.out.println("took: " + response.getTook());
  277. System.out.println("timeout: " + response.isTimedOut());
  278. System.out.println("total: " + hits.getTotalHits());
  279. System.out.println("MaxScore: " + hits.getMaxScore());
  280. System.out.println("hits------------->");
  281. for (SearchHit hit : hits) {
  282. // 输出每条查询的结果信息
  283. System.out.println(hit.getSourceAsString());
  284. }
  285. System.out.println("<-----------------");
  286. }
  287. // 分组统计
  288. public static void groupQuery(RestHighLevelClient client) throws IOException {
  289. // 创建搜索请求对象
  290. SearchRequest request = new SearchRequest();
  291. request.indices("student");
  292. // 构建查询的请求体
  293. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  294. sourceBuilder.aggregation(AggregationBuilders.terms("age_group_by").field("age"));
  295. // 设置请求体
  296. request.source(sourceBuilder);
  297. // 客户端发送请求,获取响应对象
  298. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  299. // 查询匹配
  300. SearchHits hits = response.getHits();
  301. System.out.println("took: " + response.getTook());
  302. System.out.println("timeout: " + response.isTimedOut());
  303. System.out.println("total: " + hits.getTotalHits());
  304. System.out.println("MaxScore: " + hits.getMaxScore());
  305. System.out.println("hits------------->");
  306. for (SearchHit hit : hits) {
  307. // 输出每条查询的结果信息
  308. System.out.println(hit.getSourceAsString());
  309. }
  310. System.out.println("<-----------------");
  311. }
  312. }

二、springboot项目集成Spring Data操作Elasticsearch

        Spring Data是一个用于简化数据库、非关系型数据库、索引库访问,并支持云服务的开源框架。  其主要目标是使得对数据的访问变得方便快捷,并支持 map reduce 框架和云计算数据服务。 Spring Data 可以极大的简化 JPA Elasticsearch …)的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。  除了 CRUD 外,还包括如分页、排序等一些常用的功能。官网地址:https://spring.io/projects/spring-data

        Spring Data Elasticsearch基于 spring data API 简化 Elasticsearch 操作,将原始操作Elasticsearch 的客户端 API 进行封装 。 Spring Data 为 Elasticsearch 项目提供集成搜索引擎。  Spring Data Elasticsearch POJO 的关键功能区域为中心的模型与 Elastichsearch 交互文档和轻松地编写一个存储索引库数据访问层。

1)pom文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.3.6.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.best</groupId>
  12. <artifactId>best-es</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>best-es</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <maven.compiler.source>8</maven.compiler.source>
  18. <maven.compiler.target>8</maven.compiler.target>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.projectlombok</groupId>
  23. <artifactId>lombok</artifactId>
  24. <version>1.16.12</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-devtools</artifactId>
  37. <scope>runtime</scope>
  38. <optional>true</optional>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.springframework.boot</groupId>
  42. <artifactId>spring-boot-starter-test</artifactId>
  43. <scope>test</scope>
  44. </dependency>
  45. <dependency>
  46. <groupId>org.elasticsearch</groupId>
  47. <artifactId>elasticsearch</artifactId>
  48. <version>7.8.0</version>
  49. </dependency>
  50. <!-- elasticsearch 的客户端 -->
  51. <dependency>
  52. <groupId>org.elasticsearch.client</groupId>
  53. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  54. <version>7.8.0</version>
  55. </dependency>
  56. <!-- elasticsearch 依赖 2.x 的 log4j -->
  57. <dependency>
  58. <groupId>org.apache.logging.log4j</groupId>
  59. <artifactId>log4j-api</artifactId>
  60. <version>2.8.2</version>
  61. </dependency>
  62. <dependency>
  63. <groupId>org.apache.logging.log4j</groupId>
  64. <artifactId>log4j-core</artifactId>
  65. <version>2.8.2</version>
  66. </dependency>
  67. <dependency>
  68. <groupId>com.fasterxml.jackson.core</groupId>
  69. <artifactId>jackson-databind</artifactId>
  70. <version>2.9.9</version>
  71. </dependency>
  72. <!-- junit 单元测试 -->
  73. <dependency>
  74. <groupId>junit</groupId>
  75. <artifactId>junit</artifactId>
  76. <version>4.12</version>
  77. </dependency>
  78. <dependency>
  79. <groupId>org.springframework.boot</groupId>
  80. <artifactId>spring-boot-test</artifactId>
  81. </dependency>
  82. <dependency>
  83. <groupId>org.springframework</groupId>
  84. <artifactId>spring-test</artifactId>
  85. </dependency>
  86. </dependencies>
  87. <build>
  88. <plugins>
  89. <plugin>
  90. <groupId>org.springframework.boot</groupId>
  91. <artifactId>spring-boot-maven-plugin</artifactId>
  92. </plugin>
  93. </plugins>
  94. </build>
  95. </project>

2)yaml

  1. # 端口号
  2. server:
  3. port: 8080
  4. # es服务地址与端口
  5. elasticsearch:
  6. host: 127.0.0.1
  7. port: 9200
  8. # 配置日志级别,开启debug日志
  9. logging:
  10. level:
  11. com:
  12. best: debug

3)数据实体类

  1. @Data
  2. @NoArgsConstructor
  3. @AllArgsConstructor
  4. @ToString
  5. @Document(indexName = "shopping", shards = 3, replicas = 1)
  6. public class Product {
  7. // 商品唯一标识, 必须有id, 这里的id 是全局唯一的标识,等同于es中的"_id"
  8. @Id
  9. private Long id;
  10. /**
  11. * type: 字段数据类型
  12. * analyzer: 分词器类型
  13. * index: 是否索引(默认:true)
  14. * Keyword: 短语, 不进行分词
  15. */
  16. // 商品名称
  17. @Field(type = FieldType.Text, analyzer = "ik_max_word")
  18. private String title;
  19. // 分类名称
  20. @Field(type = FieldType.Keyword)
  21. private String category;
  22. // 商品价格
  23. @Field(type = FieldType.Double)
  24. private Double price;
  25. // 图片地址
  26. @Field(type = FieldType.Keyword, index = false)
  27. private String images;
  28. }

4)配置类

        ElasticsearchRestTemplate是spring-data-elasticsearch项目中的一个类,和其他spring项目中的 template类似。在新版的spring-data-elasticsearch 中,ElasticsearchRestTemplate 代替了原来的ElasticsearchTemplate。原因是ElasticsearchTemplate基于TransportClient,TransportClient即将在8.x 以后的版本中移除。

        我们推荐使用ElasticsearchRestTemplate。ElasticsearchRestTemplate基于RestHighLevelClient客户端的。需要自定义配置类,继承AbstractElasticsearchConfiguration,并实现elasticsearchClient()抽象方法,创建RestHighLevelClient对象。

AbstractElasticsearchConfiguration源码:

  1. public abstract class AbstractElasticsearchConfiguration extends ElasticsearchConfigurationSupport {
  2. //需重写本方法
  3. public abstract RestHighLevelClient elasticsearchClient();
  4. @Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
  5. public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter) {
  6. return new ElasticsearchRestTemplate(elasticsearchClient(), elasticsearchConverter);
  7. }
  8. }

        需要自定义配置类,继承AbstractElasticsearchConfiguration,并实现elasticsearchClient()抽象方法,创建RestHighLevelClient对象。 

  1. @Data
  2. @Configuration
  3. @ConfigurationProperties(prefix = "elasticsearch")
  4. public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
  5. private String host;
  6. private Integer port;
  7. @Override
  8. public RestHighLevelClient elasticsearchClient() {
  9. RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
  10. return new RestHighLevelClient(builder);
  11. }
  12. }

5)Dao数据访问对象

  1. @Repository
  2. public interface ProductDao extends ElasticsearchRepository<Product, Long> {
  3. }

6)索引操作

  1. @SpringBootTest
  2. class BestEsApplicationTests {
  3. @Autowired
  4. private ElasticsearchRestTemplate elasticsearchRestTemplate;
  5. @Test
  6. public void creatIndex() {
  7. // 创建索引并增加映射配置
  8. // 创建索引,系统初始化会自动创建索引
  9. System.out.println("创建索引");
  10. }
  11. @Test
  12. public void deleteIndex() {
  13. boolean flag = elasticsearchRestTemplate.deleteIndex(Product.class);
  14. System.out.println("删除索引: " + flag);
  15. }
  16. }

7)文档操作

  1. @SpringBootTest
  2. public class SpringDataEsProductDaoTest {
  3. @Autowired
  4. private ProductDao productDao;
  5. /**
  6. * 新增
  7. */
  8. @Test
  9. public void save(){
  10. Product product = new Product();
  11. product.setId(2L);
  12. product.setTitle("华为手机");
  13. product.setCategory("手机");
  14. product.setPrice(2999.0);
  15. product.setImages("http://www.test/hw.jpg");
  16. productDao.save(product);
  17. }
  18. //POSTMAN, GET http://localhost:9200/shopping/_doc/2
  19. //修改
  20. @Test
  21. public void update(){
  22. Product product = new Product();
  23. product.setId(2L);
  24. product.setTitle("小米 2 手机");
  25. product.setCategory("手机");
  26. product.setPrice(9999.0);
  27. product.setImages("http://www.test/xm.jpg");
  28. productDao.save(product);
  29. }
  30. //POSTMAN, GET http://localhost:9200/shopping/_doc/2
  31. //根据 id 查询
  32. @Test
  33. public void findById(){
  34. Product product = productDao.findById(2L).get();
  35. System.out.println(product);
  36. }
  37. @Test
  38. public void findAll(){
  39. Iterable<Product> products = productDao.findAll();
  40. for (Product product : products) {
  41. System.out.println(product);
  42. }
  43. }
  44. //删除
  45. @Test
  46. public void delete(){
  47. Product product = new Product();
  48. product.setId(2L);
  49. productDao.delete(product);
  50. }
  51. //POSTMAN, GET http://localhost:9200/shopping/_doc/2
  52. //批量新增
  53. @Test
  54. public void saveAll(){
  55. List<Product> productList = new ArrayList<>();
  56. for (int i = 0; i < 10; i++) {
  57. Product product = new Product();
  58. product.setId(Long.valueOf(i));
  59. product.setTitle("["+i+"]小米手机");
  60. product.setCategory("手机");
  61. product.setPrice(1999.0 + i);
  62. product.setImages("http://www.test/xm.jpg");
  63. productList.add(product);
  64. }
  65. productDao.saveAll(productList);
  66. }
  67. //分页查询
  68. @Test
  69. public void findByPageable(){
  70. //设置排序(排序方式,正序还是倒序,排序的 id)
  71. Sort sort = Sort.by(Sort.Direction.DESC,"id");
  72. int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页
  73. int pageSize = 5;//每页显示多少条
  74. //设置查询分页
  75. PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
  76. //分页查询
  77. Page<Product> productPage = productDao.findAll(pageRequest);
  78. for (Product Product : productPage.getContent()) {
  79. System.out.println(Product);
  80. }
  81. }
  82. }

8)文档搜索

  1. @SpringBootTest
  2. public class SpringDataEsSearchTest {
  3. @Autowired
  4. private ProductDao productDao;
  5. /**
  6. * term 查询
  7. * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
  8. */
  9. @Test
  10. public void termQuery(){
  11. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "小米");
  12. Iterable<Product> products = productDao.search(termQueryBuilder);
  13. for (Product product : products) {
  14. System.out.println(product);
  15. }
  16. }
  17. /**
  18. * term 查询加分页
  19. */
  20. @Test
  21. public void termQueryByPage(){
  22. int currentPage= 0 ;
  23. int pageSize = 5;
  24. //设置查询分页
  25. PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
  26. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
  27. Iterable<Product> products =
  28. productDao.search(termQueryBuilder,pageRequest);
  29. for (Product product : products) {
  30. System.out.println(product);
  31. }
  32. }
  33. }

参考原文地址: 

三、springboot项目集成bboss操作elasticsearch

1)pom文件和配置

pom文件引入依赖:

  1. <dependency>
  2. <groupId>com.bbossgroups.plugins</groupId>
  3. <artifactId>bboss-elasticsearch-rest-jdbc</artifactId>
  4. <version>6.1.8</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.bbossgroups.plugins</groupId>
  8. <artifactId>bboss-elasticsearch-spring-boot-starter</artifactId>
  9. <version>6.1.8</version>
  10. </dependency>

application.properties配置:

  1. ##ES集群配置,支持x-pack和searchguard
  2. #spring.elasticsearch.bboss.elasticUser=elastic
  3. #spring.elasticsearch.bboss.elasticPassword=changeme
  4. spring.elasticsearch.bboss.elasticsearch.rest.hostNames=192.168.57.128:9200
  5. #spring.elasticsearch.bboss.elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282
  6. ##https配置,添加https://协议头
  7. #spring.elasticsearch.bboss.default.elasticsearch.rest.hostNames=https://10.180.211.27:9280,https://10.180.211.27:9281,https://10.180.211.27:9282
  8. spring.elasticsearch.bboss.elasticsearch.dateFormat=yyyy.MM.dd
  9. spring.elasticsearch.bboss.elasticsearch.timeZone=Asia/Shanghai
  10. spring.elasticsearch.bboss.elasticsearch.ttl=2d
  11. #在控制台输出脚本调试开关showTemplate,false关闭,true打开,同时log4j至少是info级别
  12. spring.elasticsearch.bboss.elasticsearch.showTemplate=true
  13. spring.elasticsearch.bboss.elasticsearch.discoverHost=false
  14. # dsl配置文件热加载扫描时间间隔,毫秒为单位,默认5秒扫描一次,<= 0时关闭扫描机制
  15. spring.elasticsearch.bboss.dslfile.refreshInterval = -1
  16. ##es client http连接池配置
  17. spring.elasticsearch.bboss.http.timeoutConnection = 50000
  18. spring.elasticsearch.bboss.http.timeoutSocket = 50000
  19. spring.elasticsearch.bboss.http.connectionRequestTimeout=50000
  20. spring.elasticsearch.bboss.http.retryTime = 1
  21. spring.elasticsearch.bboss.http.maxLineLength = -1
  22. spring.elasticsearch.bboss.http.maxHeaderCount = 200
  23. spring.elasticsearch.bboss.http.maxTotal = 400
  24. spring.elasticsearch.bboss.http.defaultMaxPerRoute = 200
  25. spring.elasticsearch.bboss.http.soReuseAddress = false
  26. spring.elasticsearch.bboss.http.soKeepAlive = false
  27. spring.elasticsearch.bboss.http.timeToLive = 3600000
  28. spring.elasticsearch.bboss.http.keepAlive = 3600000
  29. spring.elasticsearch.bboss.http.keystore =
  30. spring.elasticsearch.bboss.http.keyPassword =
  31. # ssl 主机名称校验,是否采用default配置,
  32. # 如果指定为default,就采用DefaultHostnameVerifier,否则采用 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
  33. spring.elasticsearch.bboss.http.hostnameVerifier =

2)getConfigRestClientUtil和getRestClientUtil区别

1. getConfigRestClientUtil获取在配置文件中根据DSL名称定义的DSL并执行它:

  1. <properties>
  2. <!--
  3. sql query
  4. -->
  5. <property name="sqlQuery">
  6. <!\[CDATA\[
  7. {"query": "SELECT * FROM dbclobdemo where channelId=#\[channelId\]"}
  8. \]\]>
  9. </property>
  10. </properties>

写入的params参数在xml文件中通过 #[参数名] 来自动注入到 DSL中

  1. ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/sql.xml");//define an instanceof ConfigRestClientUtil,It's single instance, multithreaded secure.
  2. Map params = new HashMap();
  3. params.put("channelId",1);
  4. List<Map> json = clientUtil.sql(Map.class,"sqlQuery",params);

2. getRestClientUtil直接执行代码中定义的DSL:

  1. ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();//define an instanceof RestClientUtil,It's single instance, multithreaded secure.
  2. List<Map> json = clientUtil.sql(Map.class,"{\\"query\\": \\"SELECT * FROM demo\\"}");

3)创建索引

1.普通创建

  1. @SpringBootTest
  2. class EsBbossTest {
  3. @Autowired
  4. private BBossESStarter bbossESStarter;
  5. /**
  6. *创建索引
  7. */
  8. @Test
  9. public void createIndex(){
  10. String result = bbossESStarter.getRestClient().createIndiceMapping("blog","");
  11. System.out.println(result);
  12. }
  13. }

2.自定义mapping

先创建一个dsl脚本文件,在里面自定义mapping规则:

  1. <propertys>
  2. <property name="create51jobIndex">//每个property中的name属性表示当前mapping的命名,一个xml文件里可设置多个dsl脚本
  3. <![CDATA[{
  4. "settings": {
  5. "number_of_shards": 1,
  6. "number_of_replicas": 1,
  7. "index.refresh_interval": "5s"
  8. },
  9. "mappings": {
  10. "properties": {
  11. "job":{
  12. "type":"text"
  13. },
  14. "company": {
  15. "type": "text"
  16. },
  17. "place": {
  18. "type": "text"
  19. },
  20. "salar": {
  21. "type": "text"
  22. },
  23. "data": {
  24. "type": "date",
  25. "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis"
  26. }
  27. }
  28. }
  29. }]]>
  30. </property>
  31. </propertys>

然后创建客户端,并且调用创建索引api:

  1. @SpringBootTest
  2. class EsBbossTest {
  3. @Autowired
  4. private BBossESStarter bbossESStarter;
  5. /**
  6. *创建索引
  7. */
  8. @Test
  9. public void createIndex(){
  10. ClientInterface clientUtil = bbossESStarter.getConfigRestClient("esmapper/job.xml");
  11. String result = clientUtil.createIndiceMapping("51job","create51jobIndex");
  12. System.out.println(result);
  13. }
  14. }

4)删除索引

  1. @SpringBootTest
  2. class EsBbossTest {
  3. @Autowired
  4. private BBossESStarter bbossESStarter;
  5. /**
  6. *删除索引
  7. */
  8. @Test
  9. public void dropIndex(){
  10. String result = bbossESStarter.getRestClient().dropIndice("blog");
  11. System.out.println(result);
  12. }
  13. }

5)判断索引是否存在

  1. @SpringBootTest
  2. class EsBbossTest {
  3. @Autowired
  4. private BBossESStarter bbossESStarter;
  5. /**
  6. *判断索引是否存在
  7. */
  8. @Test
  9. public void indexIsExists(){
  10. boolean exist = bbossESStarter.getRestClient().existIndice("51job");
  11. System.out.println(exist);
  12. }
  13. }

6)判断索引类型是否存在

  1. @SpringBootTest
  2. class EsBbossTest {
  3. @Autowired
  4. private BBossESStarter bbossESStarter;
  5. /**
  6. *判断索引类型是否存在
  7. */
  8. @Test
  9. public void typeIsExists(){
  10. boolean exist = bbossESStarter.getRestClient().existIndiceType("51job","_doc");
  11. System.out.println(exist);
  12. }
  13. }

7)添加单个文档

  1. @SpringBootTest
  2. class EsBbossTest {
  3. @Autowired
  4. private BBossESStarter bbossESStarter;
  5. /**
  6. *指定索引添加单个文档
  7. */
  8. @Test
  9. public void addDocument(){
  10. Qcpage qcpage=new Qcpage();
  11. qcpage.setCompany("xxxxxx有限公司").setData("2022-11-22 21:18:12").setJob("Java开发工程师").setPlace("深圳南山").setSalar("13000/月");
  12. String result = bbossESStarter.getRestClient().addDocument("51job",qcpage);
  13. System.out.println(result);
  14. }
  15. }

8)批量添加文档

  1. @SpringBootTest
  2. class EsBbossTest {
  3. @Autowired
  4. private BBossESStarter bbossESStarter;
  5. @Autowired
  6. QcpageService qcpageService;
  7. /**
  8. *批量添加文档(此处从mysql取出来1300条数据测试)
  9. */
  10. @Test
  11. public void batchAddDocument(){
  12. List<Qcpage> list=qcpageService.list();
  13. long startTime = System.currentTimeMillis();
  14. String result = bbossESStarter.getRestClient().addDocuments("51job",list);
  15. long endTime = System.currentTimeMillis();
  16. System.out.println("添加"+list.size()+"条数据耗时:" + (endTime - startTime)/1000 + "s");
  17. System.out.println(result);
  18. }
  19. }

9)查询单个文档

  1. @SpringBootTest
  2. class EsBbossTest {
  3. @Autowired
  4. private BBossESStarter bbossESStarter;
  5. /**
  6. *查询一个文档
  7. */
  8. @Test
  9. public void getDocument(){
  10. String result = bbossESStarter.getRestClient().getDocument("51job","7pJsGXMBBreT5daW4X1w");
  11. System.out.println(result);
  12. }
  13. }

参考原文地址:http://t.csdn.cn/hm0y7

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/68408?site
推荐阅读
相关标签
  

闽ICP备14008679号