当前位置:   article > 正文

spring boot学习第八篇:操作elastic search的索引和索引中的数据

spring boot学习第八篇:操作elastic search的索引和索引中的数据

前提参考:elastic search入门-CSDN博客

前提说明:已经安装好了elastic search 7.x版本,我的es版本是7.11.1

1、 pom.xml文件内容如下:

  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.6.4</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.hmblogs</groupId>
  12. <artifactId>hmblogs</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>hmblogs</name>
  15. <description>hmblogs</description>
  16. <properties>
  17. <java.version>8</java.version>
  18. <druid.version>1.2.8</druid.version>
  19. <log4jdbc.version>1.16</log4jdbc.version>
  20. <es.version>7.9.2</es.version>
  21. </properties>
  22. <dependencies>
  23. <!-- druid数据源驱动 -->
  24. <dependency>
  25. <groupId>com.alibaba</groupId>
  26. <artifactId>druid-spring-boot-starter</artifactId>
  27. <version>${druid.version}</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. <!-- mybatis -->
  39. <dependency>
  40. <groupId>com.baomidou</groupId>
  41. <artifactId>mybatis-plus-boot-starter</artifactId>
  42. <version>3.5.3.1</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.boot</groupId>
  46. <artifactId>spring-boot-starter-web</artifactId>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-test</artifactId>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.projectlombok</groupId>
  54. <artifactId>lombok</artifactId>
  55. <optional>true</optional>
  56. </dependency>
  57. <!--Mysql依赖包-->
  58. <dependency>
  59. <groupId>mysql</groupId>
  60. <artifactId>mysql-connector-java</artifactId>
  61. <scope>runtime</scope>
  62. </dependency>
  63. <!--lombok插件-->
  64. <dependency>
  65. <groupId>org.projectlombok</groupId>
  66. <artifactId>lombok</artifactId>
  67. <optional>true</optional>
  68. </dependency>
  69. <!--监控sql日志-->
  70. <dependency>
  71. <groupId>org.bgee.log4jdbc-log4j2</groupId>
  72. <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
  73. <version>${log4jdbc.version}</version>
  74. </dependency>
  75. <dependency>
  76. <groupId>com.alibaba</groupId>
  77. <artifactId>fastjson</artifactId>
  78. <version>1.2.9</version>
  79. </dependency>
  80. <dependency>
  81. <groupId>redis.clients</groupId>
  82. <artifactId>jedis</artifactId>
  83. </dependency>
  84. <dependency>
  85. <groupId>org.apache.kafka</groupId>
  86. <artifactId>kafka-clients</artifactId>
  87. </dependency>
  88. <dependency>
  89. <groupId>org.springframework.kafka</groupId>
  90. <artifactId>spring-kafka</artifactId>
  91. </dependency>
  92. <!-- high client-->
  93. <dependency>
  94. <groupId>org.elasticsearch.client</groupId>
  95. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  96. <version>${es.version}</version>
  97. <exclusions>
  98. <exclusion>
  99. <groupId>org.elasticsearch</groupId>
  100. <artifactId>elasticsearch</artifactId>
  101. </exclusion>
  102. <exclusion>
  103. <groupId>org.elasticsearch.client</groupId>
  104. <artifactId>elasticsearch-rest-client</artifactId>
  105. </exclusion>
  106. </exclusions>
  107. </dependency>
  108. <!-- rest-high-level-client 依赖如下2个jar -->
  109. <dependency>
  110. <groupId>org.elasticsearch</groupId>
  111. <artifactId>elasticsearch</artifactId>
  112. <version>${es.version}</version>
  113. </dependency>
  114. <dependency>
  115. <groupId>org.elasticsearch.client</groupId>
  116. <artifactId>elasticsearch-rest-client</artifactId>
  117. <version>${es.version}</version>
  118. </dependency>
  119. <dependency>
  120. <groupId>junit</groupId>
  121. <artifactId>junit</artifactId>
  122. </dependency>
  123. </dependencies>
  124. <build>
  125. <plugins>
  126. <plugin>
  127. <groupId>org.springframework.boot</groupId>
  128. <artifactId>spring-boot-maven-plugin</artifactId>
  129. </plugin>
  130. </plugins>
  131. </build>
  132. </project>

2、application.yml文件内容如下:

  1. server:
  2. port: 8081
  3. servlet.context-path: /
  4. #配置数据源
  5. spring:
  6. datasource:
  7. druid:
  8. db-type: com.alibaba.druid.pool.DruidDataSource
  9. driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
  10. url: jdbc:log4jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:eladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
  11. username: ${DB_USER:root}
  12. password: ${DB_PWD:123456}
  13. redis:
  14. host: localhost
  15. port: 6379
  16. password: heming
  17. database: 10
  18. es:
  19. host: 43.138.0.199
  20. port: 9200
  21. scheme: http

3、BackendApplication.java文件内容如下:

  1. package com.hmblogs.backend;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class BackendApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(BackendApplication.class, args);
  8. }
  9. }

4、测试验证,ElasticsearchClientTest.java文件内容如下:

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.hmblogs.backend.entity.Users;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  5. import org.elasticsearch.action.bulk.BulkRequest;
  6. import org.elasticsearch.action.bulk.BulkResponse;
  7. import org.elasticsearch.action.delete.DeleteRequest;
  8. import org.elasticsearch.action.delete.DeleteResponse;
  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.xcontent.XContentType;
  22. import org.elasticsearch.index.query.*;
  23. import org.elasticsearch.search.SearchHit;
  24. import org.elasticsearch.search.SearchHits;
  25. import org.elasticsearch.search.builder.SearchSourceBuilder;
  26. import org.junit.Test;
  27. import org.junit.runner.RunWith;
  28. import org.springframework.beans.factory.annotation.Autowired;
  29. import org.springframework.boot.test.context.SpringBootTest;
  30. import org.springframework.stereotype.Component;
  31. import org.springframework.test.context.junit4.SpringRunner;
  32. import java.io.IOException;
  33. import java.util.ArrayList;
  34. import java.util.HashMap;
  35. import java.util.List;
  36. import java.util.Map;
  37. @Slf4j
  38. //@Component
  39. @RunWith(SpringRunner.class)
  40. @SpringBootTest
  41. public class ElasticsearchClientTest {
  42. @Autowired
  43. private RestHighLevelClient client;
  44. String index = "users";
  45. /**
  46. * 创建索引
  47. *
  48. * @throws IOException
  49. */
  50. @Test
  51. public void createIndex() throws IOException {
  52. CreateIndexRequest indexRequest = new CreateIndexRequest(index);
  53. CreateIndexResponse response = client.indices()
  54. .create(indexRequest, RequestOptions.DEFAULT);
  55. log.info("创建索引:"+response.isAcknowledged());
  56. }
  57. /**
  58. * 判断索引是否存在
  59. *
  60. * @throws IOException
  61. */
  62. @Test
  63. public void indexExists() throws IOException {
  64. GetIndexRequest request = new GetIndexRequest(index);
  65. boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
  66. log.info("索引是否存在:"+exists);
  67. }
  68. /**
  69. * 添加文档
  70. *
  71. * @throws IOException
  72. */
  73. @Test
  74. public void addDoc() throws IOException {
  75. IndexRequest request = new IndexRequest(index);
  76. String source = JSONObject.toJSONString(new Users(10000, "逍遥", 30));
  77. // 手动设置id
  78. // request.id("10000");
  79. request.source(source, XContentType.JSON);
  80. IndexResponse response = client.index(request, RequestOptions.DEFAULT);
  81. log.info("添加文档:"+response.getResult());
  82. }
  83. /**
  84. * 批量添加文档
  85. */
  86. @Test
  87. public void batchAddDoc() throws IOException {
  88. BulkRequest bulkRequest = new BulkRequest();
  89. List<IndexRequest> requests = generateRequests();
  90. for (IndexRequest indexRequest : requests) {
  91. bulkRequest.add(indexRequest);
  92. }
  93. BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
  94. log.info("批量添加结果:"+!responses.hasFailures());
  95. }
  96. public List<IndexRequest> generateRequests() {
  97. List<IndexRequest> requests = new ArrayList<>();
  98. requests.add(generateNewsRequest(1, "小明", 22));
  99. requests.add(generateNewsRequest(2, "隔壁老王", 30));
  100. requests.add(generateNewsRequest(3, "lily", 25));
  101. return requests;
  102. }
  103. public IndexRequest generateNewsRequest(Integer id, String name, Integer age) {
  104. IndexRequest indexRequest = new IndexRequest(index);
  105. String source = JSONObject.toJSONString(new Users(id, name, age));
  106. indexRequest.source(source, XContentType.JSON);
  107. return indexRequest;
  108. }
  109. /**
  110. * 更新文档
  111. *
  112. * @throws IOException
  113. */
  114. @Test
  115. public void updateDoc() throws IOException {
  116. UpdateRequest updateRequest = new UpdateRequest(index, "AmxCP40BM8-M0To1vOET");
  117. Map<String, Object> params = new HashMap<>();
  118. params.put("id", "1");
  119. params.put("name", "逍遥");
  120. params.put("age", 33);
  121. params.put("hobby", "唱歌,跳舞,网上冲浪,看电影,旅行");
  122. updateRequest.doc(params);
  123. UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
  124. log.info("修改文档结果:"+response.getResult());
  125. }
  126. /**
  127. * 搜索
  128. *
  129. * @throws IOException
  130. */
  131. @Test
  132. public void search() throws IOException {
  133. SearchRequest request = new SearchRequest(index);
  134. SearchSourceBuilder builder = new SearchSourceBuilder();
  135. BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
  136. boolQueryBuilder
  137. .must(new RangeQueryBuilder("age").from(20).to(30))
  138. .must(new TermQueryBuilder("id", 3));
  139. builder.query(boolQueryBuilder);
  140. request.source(builder);
  141. log.info("搜索语句为: " + request.source().toString());
  142. SearchResponse search = client.search(request, RequestOptions.DEFAULT);
  143. log.info("搜索结果为:"+search);
  144. SearchHits hits = search.getHits();
  145. SearchHit[] hitsArr = hits.getHits();
  146. for (SearchHit documentFields : hitsArr) {
  147. log.info(documentFields.getSourceAsString());
  148. }
  149. }
  150. @Test
  151. public void search2() {
  152. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  153. sourceBuilder.from(0);
  154. sourceBuilder.size(10);
  155. sourceBuilder.fetchSource(new String[]{"name", "age"}, new String[]{});
  156. MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("hobby", "唱歌,跳舞,网上冲浪,看电影,旅行");
  157. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "逍遥");
  158. RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
  159. rangeQueryBuilder.gte(20);
  160. rangeQueryBuilder.lte(40);
  161. BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
  162. boolBuilder.must(matchQueryBuilder);
  163. boolBuilder.must(termQueryBuilder);
  164. boolBuilder.must(rangeQueryBuilder);
  165. sourceBuilder.query(boolBuilder);
  166. SearchRequest searchRequest = new SearchRequest(index);
  167. searchRequest.source(sourceBuilder);
  168. try {
  169. log.info("搜索语句为: " + searchRequest.source().toString());
  170. SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
  171. log.info("搜索结果为:"+search);
  172. SearchHits hits = search.getHits();
  173. SearchHit[] hitsArr = hits.getHits();
  174. for (SearchHit documentFields : hitsArr) {
  175. log.info(documentFields.getSourceAsString());
  176. }
  177. } catch (IOException e) {
  178. log.error("搜索报错:{}",e);
  179. }
  180. }
  181. /**
  182. * 删除文档
  183. * @throws IOException
  184. */
  185. @Test
  186. public void deleteDoc() throws IOException {
  187. DeleteRequest deleteRequest = new DeleteRequest(index, "3g8vP40Bi8WQ8ue06wWd");
  188. DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
  189. log.info("删除结果为:"+response.getResult());
  190. }
  191. /**
  192. * 删除索引
  193. * @throws IOException
  194. */
  195. @Test
  196. public void deleteIndex() throws IOException {
  197. DeleteIndexRequest request = new DeleteIndexRequest(index);
  198. AcknowledgedResponse response = client.indices()
  199. .delete(request, RequestOptions.DEFAULT);
  200. log.info("删除索引结果为:"+response.isAcknowledged());
  201. }
  202. }

每个方法的作用见注释说明,

 这里点击Run search2()

然后查看console的log,验证OK

这样写代码,还是不够灵活,能不能执行自定义的SQL或者DSL语句,这样就可以不用去想办法看下Builder那些类对象怎么设置了。

其实,要想实现这样的效果,就是调用http接口而已

RestTemplateUtil.java文件内容如下:

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.http.HttpEntity;
  3. import org.springframework.http.HttpHeaders;
  4. import org.springframework.http.MediaType;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.web.client.RestTemplate;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. @Component
  10. public class RestTemplateUtil {
  11. @Autowired
  12. private RestTemplate restTemplate;
  13. public String post(String url,Map map){
  14. // 设置请求头属性
  15. HttpHeaders httpHeaders = new HttpHeaders();
  16. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  17. HttpEntity httpEntity = new HttpEntity(map, httpHeaders);
  18. String results = restTemplate.postForObject(url, httpEntity, String.class);
  19. return results;
  20. }
  21. }

ElasticsearchClientSqlDslTest.java类文件内容如下:

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringRunner;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. @Slf4j
  10. //@Component
  11. @RunWith(SpringRunner.class)
  12. @SpringBootTest
  13. public class ElasticsearchClientSqlDslTest {
  14. @Autowired
  15. private RestTemplateUtil restTemplateUtil;
  16. @Test
  17. public void complexQueryEsData() {
  18. // 请求参数
  19. Map map = new HashMap<>();
  20. map.put("query", "SELECT id,name,age FROM users order by name desc limit 6");
  21. String url = "http://43.138.0.199:9200/_sql?format=json";
  22. String studentData = restTemplateUtil.post(url, map);
  23. log.info("studentData:"+studentData);
  24. }
  25. }

执行后,查出了数据,console如下截图:

返回数据如下:

{"columns":[{"name":"id","type":"long"},{"name":"name","type":"text"},{"name":"age","type":"long"}],"rows":[[2,"隔壁老王",30],[1,"逍遥",33],[1,"小明",22],[3,"lily",25]]}

 

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

闽ICP备14008679号