当前位置:   article > 正文

springboot 操作es 之elasticsearch-rest-high-level-client

elasticsearch-rest-high-level-client

1.使用elasticsearch高级客户端api

官网api

Java High Level REST Client | Java REST Client [7.15] | Elastic

2.本人用的elasticsearch版本就是7.14,使用api版本是7.15.2 ,使用es版本对应版本或者高一点版本没问题 以免造成不必要麻烦

3.可以边看官网边看这个例子 ,废话不多说,先上依赖上代码

  1. <!--es 高级客户端 包含org.elasticsearch-->
  2. <dependency>
  3. <groupId>org.elasticsearch.client</groupId>
  4. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  5. <version>7.15.2</version>
  6. </dependency>
  7. <!--es bug导致运行异常,缺少包,优先引入上面的,如果不报错,下面这个不需要引入,-->
  8. <dependency>
  9. <groupId>org.elasticsearch</groupId>
  10. <artifactId>elasticsearch</artifactId>
  11. <version>7.15.2</version>
  12. </dependency>

其实引入一个

elasticsearch-rest-high-level-client 这个主依赖包含 org.elasticsearch这个依赖,但是本人遇到一个问题,启动项目会报错

Caused by: java.lang.ClassNotFoundException: org.elasticsearch.common.xcontent.DeprecationHandler

 导致jar引入不完整导致的,咱们在引入一遍,确保jar的完整

 4.解决maven依赖问题,我们就可以搞点测试类玩玩啦

springboot 下面 引入一下测试类吧,或者不用测试类都可以。有的同学项目创建时候不勾选test依赖,可以引入下

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. <scope>test</scope>
  5. </dependency>

(2)其实安装个Maven Dependency Helper这个插件不错,帮你找到你设置镜像查到依赖

简直牛B666

 

,这里不用版本,默认跟boot版本一致。

4.下一步就是配置啦springboot配置一下 连接es的config类,让spring扫描到,直接上代码啦

  1. package com.example.helloshirodemo.common.es;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.http.HttpHost;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.client.RestClient;
  6. import org.elasticsearch.client.RestHighLevelClient;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import java.io.IOException;
  11. /**
  12. * @author zhang
  13. * @version 1.0
  14. * @date 2022/1/19 9:26
  15. */
  16. @Configuration
  17. @Slf4j
  18. public class ElasticSearchConfig {
  19. public static final RequestOptions COMMON_OPTIONS;
  20. //hostName 代表ip
  21. @Value("${elasticsearch.cluster-nodes}")
  22. private String hostName;
  23. //因为咱们这个高级客户端rest 是基于http 咱们使用端口9200 ,而9300是tcp
  24. @Value("${elasticsearch.port}")
  25. private int port;
  26. static {
  27. // RequestOptions类保存了请求的部分,这些部分应该在同一个应用程序中的许多请求之间共享。
  28. // 创建一个singqleton实例,并在所有请求之间共享它。可以设置请求头之类的一些配置
  29. RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
  30. // builder.addHeader("Authorization", "Bearer " + TOKEN); //增加需要的请求 头
  31. // builder.setHttpAsyncResponseConsumerFactory(
  32. // new HttpAsyncResponseConsumerFactory
  33. // .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 *1024));
  34. COMMON_OPTIONS = builder.build();
  35. }
  36. //创建ES实例
  37. @Bean
  38. public RestHighLevelClient restHighLevelClient() throws IOException {
  39. RestHighLevelClient client = new RestHighLevelClient(
  40. RestClient.builder(new HttpHost(
  41. hostName, port, "http"
  42. )));
  43. return client;
  44. }
  45. }

9200用于外部通讯,基于http协议,程序与es的通信使用9200端口。

9300jar之间就是通过tcp协议通信,遵循tcp协议,es集群中的节点之间也通过9300端口进行通信。

5.配置完毕,就可以使用啦,操作一下api 吧,创建个测试类

项目结构 要对应

  1. package com.example.helloshirodemo;
  2. import com.example.helloshirodemo.common.es.ElasticSearchConfig;
  3. import org.elasticsearch.ElasticsearchException;
  4. import org.elasticsearch.action.ActionListener;
  5. import org.elasticsearch.action.DocWriteResponse;
  6. import org.elasticsearch.action.get.GetRequest;
  7. import org.elasticsearch.action.get.GetResponse;
  8. import org.elasticsearch.action.index.IndexRequest;
  9. import org.elasticsearch.action.index.IndexResponse;
  10. import org.elasticsearch.action.search.SearchRequest;
  11. import org.elasticsearch.action.search.SearchResponse;
  12. import org.elasticsearch.action.support.AdapterActionFuture;
  13. import org.elasticsearch.client.Cancellable;
  14. import org.elasticsearch.client.ElasticsearchClient;
  15. import org.elasticsearch.client.RestHighLevelClient;
  16. import org.elasticsearch.client.core.MainResponse;
  17. import org.elasticsearch.common.unit.Fuzziness;
  18. import org.elasticsearch.common.xcontent.XContentBuilder;
  19. import org.elasticsearch.common.xcontent.XContentType;
  20. import org.elasticsearch.core.TimeValue;
  21. import org.elasticsearch.index.query.MatchQueryBuilder;
  22. import org.elasticsearch.index.query.QueryBuilders;
  23. import org.elasticsearch.search.SearchHit;
  24. import org.elasticsearch.search.builder.SearchSourceBuilder;
  25. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  26. import org.junit.jupiter.api.Test;
  27. import org.springframework.beans.factory.annotation.Autowired;
  28. import org.springframework.boot.test.context.SpringBootTest;
  29. import javax.naming.directory.SearchResult;
  30. import java.io.IOException;
  31. import java.net.ConnectException;
  32. import java.util.Date;
  33. import java.util.Map;
  34. import java.util.UUID;
  35. import java.util.concurrent.ExecutionException;
  36. import java.util.concurrent.TimeUnit;
  37. /**
  38. * @author zhang
  39. * @version 1.0
  40. * @date 2022/1/19 10:04
  41. */
  42. @SpringBootTest
  43. public class Test1 {
  44. @Autowired
  45. private RestHighLevelClient restHighLevelClient;
  46. /*创建索引 插入文档*/
  47. @Test
  48. public void test001() throws IOException {
  49. IndexRequest indexRequest = new IndexRequest("indexrequest");
  50. indexRequest.id(UUID.randomUUID().toString().replaceAll("-",""));
  51. String jsonString = "{" +
  52. "\"user\":\"kimchy\"," +
  53. "\"postDate\":\"2013-01-30\"," +
  54. "\"message\":\"trying out Elasticsearch\"" +
  55. "}";
  56. indexRequest.source(jsonString, XContentType.JSON);
  57. IndexResponse index = restHighLevelClient.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
  58. DocWriteResponse.Result result = index.getResult();
  59. if(DocWriteResponse.Result.CREATED.equals(index.getResult())){
  60. System.out.println("创建索引 插入文档完毕!!");
  61. }
  62. }
  63. /*获取指定索引下的 id 文档*/
  64. @Test
  65. public void test002() throws IOException {
  66. GetRequest getRequest = new GetRequest("indexrequest");
  67. getRequest.id("0e8e3045e7da4c07a66cf36fb0725835");
  68. GetResponse documentFields = restHighLevelClient.get(getRequest, ElasticSearchConfig.COMMON_OPTIONS);
  69. Map<String, Object> source = documentFields.getSource();
  70. System.out.println(source);
  71. }
  72. @Test
  73. public void test003() throws IOException {
  74. try {
  75. if(restHighLevelClient.ping(ElasticSearchConfig.COMMON_OPTIONS)){
  76. System.out.println("链接成功es");
  77. }
  78. }catch (Exception e){
  79. if(e instanceof ElasticsearchException){
  80. System.out.println("ConnectException链接失败");
  81. }
  82. }
  83. }
  84. /*模糊查询*/
  85. @Test
  86. public void test004() throws IOException {
  87. //创建搜索请求。如果没有参数,这将对所有索引运行。
  88. SearchRequest searchRequest = new SearchRequest("t_blog");
  89. //大多数搜索参数都添加到SearchSourceBuilder中。它为进入搜索请求主体的所有内容提供了setter。
  90. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  91. MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", "标题2");
  92. matchQueryBuilder.fuzziness(Fuzziness.AUTO); //开启模糊性查询
  93. matchQueryBuilder.prefixLength(3); //模糊前缀
  94. matchQueryBuilder.maxExpansions(10); //设置最大扩展选项
  95. // searchSourceBuilder.query(QueryBuilders.matchQuery("text","标题2"));
  96. searchSourceBuilder.query(matchQueryBuilder);
  97. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  98. searchRequest.source(searchSourceBuilder);
  99. SearchResponse search = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
  100. SearchHit[] hits = search.getHits().getHits();
  101. for (SearchHit hit : hits) {
  102. System.out.println(hit);
  103. }
  104. }
  105. /*高亮查询*/
  106. @Test
  107. public void heihtQueryTest01() throws IOException {
  108. //指定搜素请求信息
  109. SearchRequest searchRequest = new SearchRequest("t_blog"); //index
  110. //创建搜素源生成器
  111. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  112. //匹配
  113. MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", "标题2");
  114. //高亮
  115. HighlightBuilder highlightBuilder = new HighlightBuilder();
  116. HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("title");
  117. highlightBuilder.preTags("<span style='color:red' >");//设置前缀
  118. highlightBuilder.postTags("</span>");//设置后缀
  119. highlightBuilder.field(highlightTitle);
  120. //设置高亮
  121. searchSourceBuilder.highlighter(highlightBuilder);
  122. //匹配器设置匹配规则
  123. searchSourceBuilder.query(matchQueryBuilder);
  124. //设置排序
  125. searchSourceBuilder.sort("createTime");
  126. //设置分页
  127. searchSourceBuilder.from(0); //页吗
  128. searchSourceBuilder.size(10);//默认命中10
  129. searchRequest.source(searchSourceBuilder);
  130. SearchResponse search = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
  131. for (SearchHit hit : search.getHits().getHits()) {
  132. Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  133. System.out.println(sourceAsMap);
  134. }
  135. }
  136. }

 

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

闽ICP备14008679号