SpringBoot整合Elasticsearch7.2.0的实现方法

作者:onlooker 时间:2023-11-09 19:22:56 

Spring boot 2.1.X整合Elasticsearch最新版的一处问题

新版本的Spring boot 2的spring-boot-starter-data-elasticsearch中支持的Elasticsearch版本是2.X,但Elasticsearch实际上已经发展到7.2.X版本了,为了更好的使用Elasticsearch的新特性,所以弃用了spring-boot-starter-data-elasticsearch依赖,而改为直接使用Spring-data-elasticsearch,以便启用对新版本支持,目前的版本对应关系如下

SpringBoot整合Elasticsearch7.2.0的实现方法

Elasticsearch(ES)有两种连接方式:transport、rest。transport通过TCP方式访问ES(只支持java),rest方式通过http API 访问ES(没有语言限制)。
ES官方建议使用rest方式, transport 在7.0版本中不建议使用,在8.X的版本中废弃。

引入依赖:


<dependency>
     <groupId>org.elasticsearch</groupId>
     <artifactId>elasticsearch</artifactId>
     <version>${elasticsearch.version}</version>
   </dependency>
   <dependency>
     <groupId>org.elasticsearch.client</groupId>
     <artifactId>elasticsearch-rest-client</artifactId>
     <version>${elasticsearch.version}</version>
   </dependency>
   <dependency>
     <groupId>org.elasticsearch.client</groupId>
     <artifactId>elasticsearch-rest-high-level-client</artifactId>
     <version>${elasticsearch.version}</version>
   </dependency>

application.yml配置:


elasticsearch:
ip: 192.168.52.132:9200

客户端连接配置类


package com.dc.elastic.configuration;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Objects;

/**
* 描述: 连接客户端
*
* @author leo
* @create 2019-08-25 13:22
*/
@Configuration
public class ElasticsearchRestClient
{
 /**
  * 超时时间设为5分钟
  */
 private static final int TIME_OUT = 5 * 60 * 1000;
 private static final int ADDRESS_LENGTH = 2;
 private static final String HTTP_SCHEME = "http";

@Value("${elasticsearch.ip}")
 String[] ipAddress;

@Bean
 public RestClientBuilder restClientBuilder() {
   System.err.println(ipAddress);
   HttpHost[] hosts = Arrays.stream(ipAddress)
       .map(this::makeHttpHost)
       .filter(Objects::nonNull)
       .toArray(HttpHost[]::new);
   return RestClient.builder(hosts);
 }

@Bean(name = "highLevelClient")
 public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder) {
   restClientBuilder.setRequestConfigCallback(
       new RestClientBuilder.RequestConfigCallback() {
         @Override
         public RequestConfig.Builder customizeRequestConfig(
             RequestConfig.Builder requestConfigBuilder) {
           return requestConfigBuilder.setSocketTimeout(TIME_OUT);
         }
       });
   //TODO 此处可以进行其它操作
   return new RestHighLevelClient(restClientBuilder);
 }

private HttpHost makeHttpHost(String s) {
   assert StringUtils.isNotEmpty(s);
   String[] address = s.split(":");
   if (address.length == ADDRESS_LENGTH) {
     String ip = address[0];
     int port = Integer.parseInt(address[1]);
     System.err.println(ip+"+"+port);
     return new HttpHost(ip, port, HTTP_SCHEME);
   } else {
     return null;
   }
 }
}

测试controller


@RequestMapping("/test")
 public void test(@RequestParam String keyword) {
   Integer pageIndex = 1;
   Integer pageSize = 5;
   String indexName = "vw_ods";
   Map<String, Object> data = new HashMap<>();
   data.put("clearacctname", keyword);

List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
   SearchRequest searchRequest = new SearchRequest(indexName);
   // searchRequest.types(indexName);
   queryBuilder(pageIndex, pageSize, data, indexName, searchRequest);
   try {
     SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
     for (SearchHit hit : response.getHits().getHits()) {
       Map<String, Object> map = hit.getSourceAsMap();
       map.put("id", hit.getId());
       result.add(map);

// 取高亮结果
       Map<String, HighlightField> highlightFields = hit.getHighlightFields();
       HighlightField highlight = highlightFields.get("clearacctname");
       Text[] fragments = highlight.fragments(); // 多值的字段会有多个值
       String fragmentString = fragments[0].string();
       System.out.println("高亮:" + fragmentString);
     }
     System.out.println("pageIndex:" + pageIndex);
     System.out.println("pageSize:" + pageSize);
     System.out.println(response.getHits().getTotalHits());
     System.out.println(result.size());
     for (Map<String, Object> map : result) {
       System.out.println(map.get("clearacctname"));
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }

private void queryBuilder(Integer pageIndex, Integer pageSize, Map<String, Object> query, String indexName,
              SearchRequest searchRequest) {
   if (query != null && !query.keySet().isEmpty()) {
     SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
     if (pageIndex != null && pageSize != null) {
       searchSourceBuilder.size(pageSize);
       if (pageIndex <= 0) {
         pageIndex = 0;
       }
       searchSourceBuilder.from((pageIndex - 1) * pageSize);
     }
     BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
     query.keySet().forEach(key -> {
       boolBuilder.must(QueryBuilders.matchQuery(key, query.get(key)));

});
     searchSourceBuilder.query(boolBuilder);

HighlightBuilder highlightBuilder = new HighlightBuilder();
     HighlightBuilder.Field highlightTitle =
         new HighlightBuilder.Field("title").preTags("<strong>").postTags("</strong>");
     highlightTitle.highlighterType("unified");
     highlightBuilder.field(highlightTitle);
     searchSourceBuilder.highlighter(highlightBuilder);

SearchRequest source = searchRequest.source(searchSourceBuilder);
   }
 }

来源:https://segmentfault.com/a/1190000020179390

标签:Spring,Boot,Elasticsearch
0
投稿

猜你喜欢

  • 使用spring容器在初始化Bean时前和后的操作

    2021-07-01 05:49:24
  • 完美解决Android App启动页有白屏闪过的问题

    2021-11-18 02:12:31
  • AQS加锁机制Synchronized相似点详解

    2023-08-04 22:36:55
  • MyBatis实现多表联合查询resultType的返回值

    2023-03-11 22:25:37
  • DoytoQuery中关于N+1查询问题解决方案详解

    2022-06-14 12:03:07
  • Unity自定义编辑器界面(Inspector界面)

    2023-01-09 08:40:46
  • Android开发应用中Broadcast Receiver组件详解

    2023-04-25 09:35:35
  • 解决@Autowired注入static接口的问题

    2022-01-02 03:16:29
  • Android实现的秒表计时器示例

    2023-04-26 11:32:56
  • java实现单人版五子棋游戏

    2021-09-03 03:24:20
  • Android Studio项目适配AndroidX(Android 9.0)的方法步骤

    2022-10-30 12:01:03
  • 详解SpringBoot统一响应体解决方案

    2023-03-08 08:54:13
  • Android控件系列之EditText使用方法

    2021-06-19 19:09:20
  • Android开发实现圆形图片功能示例

    2023-07-12 08:43:54
  • java语法糖之jdk迭代的新特性汇总

    2022-07-09 10:05:19
  • C#实现带阴历显示的日期代码

    2023-12-11 02:19:04
  • springMVC的生命周期详解

    2022-10-29 22:27:40
  • Android 仿网易新闻客户端分类排序功能

    2023-12-19 13:07:52
  • Java关系操作符简写介绍

    2023-12-25 12:56:29
  • WinForm实现最小化到系统托盘方法实例详解

    2023-10-05 05:53:30
  • asp之家 软件编程 m.aspxhome.com