SpringBoot集成Elasticsearch7.4 实战(二)

news/2023/6/9 20:14:19

1、前言

本篇文章主要讲的是:在Springboot环境下,利用JAVA环境操作索引,集成SpringBoot等相关知识

2. SpringBoot集成

开发工具,这里选择的是IDEA 2019.2,构建Maven工程等一堆通用操作,不清楚的自行百度。

2.1. POM配置

我这边选择 elasticsearch-rest-high-level-client 方式来集成,发现这有个坑,开始没注意,踩了好久,就是要排除掉 elasticsearch、elasticsearch-rest-client ,这里没有选择 spring-boot-starter-data-elasticsearch ,因为最新版的 starter 现在依然是6.x版本号,并没有集成 elasticsearch7.4.0,导致使用过程中有很多版本冲突,读者在选择的时候多加留意。

<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.4.0</version><exclusions><exclusion><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId></exclusion><exclusion><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId></exclusion></exclusions>
</dependency>
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>7.4.0</version>
</dependency>
<dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.4.0</version>
</dependency>

2.2. yml配置

server:port: 9090
spring:datasource:name: mysqltype: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTCusername: rootpassword: 123456druid:initial-size: 5min-idle: 5max-active: 20max-wait: 30000time-between-eviction-runs-millis: 60000min-evictable-idle-time-millis: 300000validation-query: select 1test-while-idle: truetest-on-borrow: falsetest-on-return: falsepool-prepared-statements: falsemax-pool-prepared-statement-per-connection-size: 20connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=6000
es:host: 192.168.147.132port: 9200scheme: httpmybatis:mapperLocations: classpath:mapper/**/*.xml

这里定义 es 节点下即 elasticsearch 的地址端口信息,修改为自己的即可。

2.3. 核心操作类

为了规范索引管理,这里将所有的操作都封装成一个基类,实现对索引的增删改查。同时还集成了对数据的单个以及批量的插入以及删除。避免针对每个索引都自己写一套实现,杜绝代码的冗余,同时这样的集成对代码的结构本身也是低侵入性。

package xyz.wongs.weathertop.base.dao;import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;
import xyz.wongs.weathertop.base.entiy.Ela1tity;import java.util.ArrayList;
import java.util.Collection;
import java.util.List;@Slf4j
@Component
public class BaseElasticDao {@AutowiredRestHighLevelClient restHighLevelClient;/*** @author wuKeFan* @See* @date 2019/10/17 17:30* @param idxName   索引名称* @param idxSQL    索引描述* @return void* @throws* @since*/public void createIndex(String idxName,String idxSQL){try {if (!this.indexExist(idxName)) {log.error(" idxName={} 已经存在,idxSql={}",idxName,idxSQL);return;}CreateIndexRequest request = new CreateIndexRequest(idxName);buildSetting(request);request.mapping(idxSQL, XContentType.JSON);//request.settings() 手工指定SettingCreateIndexResponse res = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);if (!res.isAcknowledged()) {throw new RuntimeException("初始化失败");}} catch (Exception e) {e.printStackTrace();System.exit(0);}}/** 断某个index是否存在* @author wuKeFan* @See* @date 2019/10/17 17:27* @param idxName index名* @return boolean* @throws* @since*/public boolean indexExist(String idxName) throws Exception {GetIndexRequest request = new GetIndexRequest(idxName);request.local(false);request.humanReadable(true);request.includeDefaults(false);request.indicesOptions(IndicesOptions.lenientExpandOpen());return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);}/** 设置分片* @author wuKeFan* @See* @date 2019/10/17 19:27* @param request* @return void* @throws* @since*/public void buildSetting(CreateIndexRequest request){request.settings(Settings.builder().put("index.number_of_shards",3).put("index.number_of_replicas",2));}/*** @author wuKeFan* @See* @date 2019/10/17 17:27* @param idxName index* @param entity    对象* @return void* @throws* @since*/public void insertOrUpdateOne(String idxName, ElasticEntity entity) {IndexRequest request = new IndexRequest(idxName);request.id(entity.getId());request.source(JSON.toJSONString(entity.getData()), XContentType.JSON);try {restHighLevelClient.index(request, RequestOptions.DEFAULT);} catch (Exception e) {throw new RuntimeException(e);}}/** 批量插入数据* @author wuKeFan* @See* @date 2019/10/17 17:26* @param idxName index* @param list 带插入列表* @return void* @throws* @since*/public void insertBatch(String idxName, List<ElasticEntity> list) {BulkRequest request = new BulkRequest();list.forEach(item -> request.add(new IndexRequest(idxName).id(item.getId()).source(JSON.toJSONString(item.getData()), XContentType.JSON)));try {restHighLevelClient.bulk(request, RequestOptions.DEFAULT);} catch (Exception e) {throw new RuntimeException(e);}}/** 批量删除* @author wuKeFan* @See* @date 2019/10/17 17:14* @param idxName index* @param idList    待删除列表* @return void* @throws* @since*/public <T> void deleteBatch(String idxName, Collection<T> idList) {BulkRequest request = new BulkRequest();idList.forEach(item -> request.add(new DeleteRequest(idxName, item.toString())));try {restHighLevelClient.bulk(request, RequestOptions.DEFAULT);} catch (Exception e) {throw new RuntimeException(e);}}/*** @author wuKeFan* @See* @date 2019/10/17 17:14* @param idxName index* @param builder   查询参数* @param c 结果类对象* @return java.util.List<T>* @throws* @since*/public <T> List<T> search(String idxName, SearchSourceBuilder builder, Class<T> c) {SearchRequest request = new SearchRequest(idxName);request.source(builder);try {SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);SearchHit[] hits = response.getHits().getHits();List<T> res = new ArrayList<>(hits.length);for (SearchHit hit : hits) {res.add(JSON.parseObject(hit.getSourceAsString(), c));}return res;} catch (Exception e) {throw new RuntimeException(e);}}/** 删除index* @author wuKeFan* @See* @date 2019/10/17 17:13* @param idxName* @return void* @throws* @since*/public void deleteIndex(String idxName) {try {if (!this.indexExist(idxName)) {log.error(" idxName={} 已经存在",idxName);return;}restHighLevelClient.indices().delete(new DeleteIndexRequest(idxName), RequestOptions.DEFAULT);} catch (Exception e) {throw new RuntimeException(e);}}/*** @author wuKeFan* @See* @date 2019/10/17 17:13* @param idxName* @param builder* @return void* @throws* @since*/public void deleteByQuery(String idxName, QueryBuilder builder) {DeleteByQueryRequest request = new DeleteByQueryRequest(idxName);request.setQuery(builder);//设置批量操作数量,最大为10000request.setBatchSize(10000);request.setConflicts("proceed");try {restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);} catch (Exception e) {throw new RuntimeException(e);}}
}

3. 实战

通过以上的集成,我们看到完成在项目中对 elasticsearch 的集成,同时也用基类,将所有可能的操作都封装起来。下来我们通过对基类的讲解,来逐个说明!

3.1. 索引管理

由于在BaseElasticDao类中createIndex方法,我在Controller层将索引名称和索引SQL封装过,详细见Github演示源码 中xyz.wongs.weathertop.palant.vo.IdxVo

3.1.1. 创建索引

我们在创建索引过程中需要先判断是否有这个索引,否则不允许创建,由于我案例采用的是手动指定indexName和Settings,大家看的过程中要特别注意下,而且还有一点indexName必须是小写,如果是大写在创建过程中会有错误

详细的代码实现见如下:


/*** @Description 创建Elastic索引* @param idxVo* @return xyz.wongs.weathertop.base.message.response.ResponseResult* @throws* @date 2019/11/19 11:07*/
@RequestMapping(value = "/createIndex",method = RequestMethod.POST)
public ResponseResult createIndex(@RequestBody IdxVo idxVo){ResponseResult response = new ResponseResult();try {//索引不存在,再创建,否则不允许创建if(!baseElasticDao.indexExist(idxVo.getIdxName())){String idxSql = JSONObject.toJSONString(idxVo.getIdxSql());log.warn(" idxName={}, idxSql={}",idxVo.getIdxName(),idxSql);baseElasticDao.createIndex(idxVo.getIdxName(),idxSql);} else{response.setStatus(false);response.setCode(ResponseCode.DUPLICATEKEY_ERROR_CODE.getCode());response.setMsg("索引已经存在,不允许创建");}} catch (Exception e) {response.setStatus(false);response.setCode(ResponseCode.ERROR.getCode());response.setMsg(ResponseCode.ERROR.getMsg());}return response;
}

创建索引需要设置分片,这里采用Settings.Builder方式,当然也可以JSON自定义方式,本文篇幅有限,不做演示。查看xyz.wongs.weathertop.base.service.BaseElasticService.buildSetting方法,这里是默认值。

index.number_of_shards:分片数
number_of_replicas:副本数

/** 设置分片* @author wuKeFan* @See* @date 2019/10/17 19:27* @param request* @return void* @throws* @since*/
public void buildSetting(CreateIndexRequest request){request.settings(Settings.builder().put("index.number_of_shards",3).put("index.number_of_replicas",2));
}

这时候我们通过Postman工具调用Controller,发现创建索引成功。

再命令行执行curl -H "Content-Type: application/json" -X GET "http://localhost:9200/_cat/indices?v",效果如图:


[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/_cat/indices?v"
health status index        uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   twitter      scSSD1SfRCio4F77Hh8aqQ   3   2          2            0      8.3kb          8.3kb
yellow open   idx_location _BJ_pOv0SkS4tv-EC3xDig   3   2          1            0        4kb            4kb
yellow open   wongs        uT13XiyjSW-VOS3GCqao8w   3   2          1            0      3.4kb          3.4kb
yellow open   idx_locat    Kr3wGU7JT_OUrRJkyFSGDw   3   2          3            0     13.2kb         13.2kb
yellow open   idx_copy_to  HouC9s6LSjiwrJtDicgY3Q   3   2          1            0        4kb            4kb

说明创建成功,这里总是通过命令行来验证,有点繁琐,既然我都有WEB服务,为什么不直接通过HTTP验证了?

3.1.2. 查看索引

我们写一个对外以HTTP+GET方式对外提供查询的服务。存在为TRUE,否则False.

/*** @Description 判断索引是否存在;存在-TRUE,否则-FALSE* @param index* @return xyz.wongs.weathertop.base.message.response.ResponseResult* @throws* @date 2019/11/19 18:48*/
@RequestMapping(value = "/exist/{index}")
public ResponseResult indexExist(@PathVariable(value = "index") String index){ResponseResult response = new ResponseResult();try {if(!baseElasticDao.isExistsIndex(index)){log.error("index={},不存在",index);response.setCode(ResponseCode.RESOURCE_NOT_EXIST.getCode());response.setMsg(ResponseCode.RESOURCE_NOT_EXIST.getMsg());} else {response.setMsg(" 索引已经存在, " + index);}} catch (Exception e) {response.setCode(ResponseCode.NETWORK_ERROR.getCode());response.setMsg(" 调用ElasticSearch 失败!");response.setStatus(false);}return response;
}

3.1.3. 删除索引

删除的逻辑就比较简单,这里就不多说。

/** 删除index* @author wuKeFan* @See* @date 2019/10/17 17:13* @param idxName* @return void* @throws* @since*/
public void deleteIndex(String idxName) {try {if (!this.indexExist(idxName)) {log.error(" idxName={} 已经存在",idxName);return;}restHighLevelClient.indices().delete(new DeleteIndexRequest(idxName), RequestOptions.DEFAULT);} catch (Exception e) {throw new RuntimeException(e);}
}

4.相关章节

一、SpringBoot集成Elasticsearch7.4 实战(一)

二、SpringBoot集成Elasticsearch7.4 实战(二)

三、SpringBoot集成Elasticsearch7.4 实战(三)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.exyb.cn/news/show-4559369.html

如若内容造成侵权/违法违规/事实不符,请联系郑州代理记账网进行投诉反馈,一经查实,立即删除!

相关文章

ABAP SMARTFORM 打印,实例细节 SAP

好久没写了&#xff0c;趁着房间前写一下最近打印的过程&#xff0c;打印也是一个比较费时费眼睛的事情&#xff0c;需要核对数据 &#xff0c;调整样式。 记录本次SMARTFORM的制作过程。事务代码&#xff1a;SMARTFORMS 首先了解制作出一个打印单必须的条件是什么&#xff0…

js打印分页、加标题、每页控制条数

js打印分页、加标题、每页控制条数 1.<body加入以下内容> <input class“btn btn-primary btn-sm” type“button” value“打印信息” id"btn_tj"οnclick“js_print()”> <c:forEach items"${tjxx}" var"item" varStatus"…

Excel 2007 设置每页打印标题

当excel文件行数较多&#xff0c;且需要将标题在打印的每一页中都进行显示打印&#xff0c;之前用excel 2003可以很简单的在“页面设置”中设置打印标题即可&#xff0c;但在07版中的设置方法就有些差异&#xff0c;现在一起来看看07版中如何设置打印标题&#xff08;个人觉得0…

垂直距页边距5厘米_Word里“函头纸打印”文号与标题间距控制方法

Word里“函头纸打印”文号与标题间距控制方法2019-01-29 12:04:212点赞3收藏0评论摘 要&#xff1a;本文探讨了Word里函头文文号和标题间距的控制方法&#xff0c;同时也分析了行距、段间距、边距等各种垂直间距。1 问题提出在办公室的工作过程中&#xff0c;经常需要用到函头纸…

vue全家桶之vuex详解

文章目录Vuex 概述1.1 组件之间共享数据的方式1.2 Vuex 是什么1.3 使用 Vuex 统一管理状态的好处什么样的数据适合存储到 Vuex 中2. Vuex 的基本使用3. Vuex 的核心概念3.1 核心概念概述3.2 State3.3 Mutation3.4 Action3.5 GetterVuex 概述 1.1 组件之间共享数据的方式 父向…

ESP32入门-NVS的flash读写测试

硬件 ① 开发板型号&#xff1a;ESP32-WROOM-32 2.软件设计 2.1代码逻辑 ①初始化NVS —> ②创建数据表 —> ③ 读写对应数据表中数据 2.1 软件应用说明 1.NVS使用说明 NVS官方说明 NVS 最适合存储一些较小的数据&#xff0c;而非字符串或二进制大对象 (BLOB) 等较…

乐鑫ESP32 NVS读错误BUG:nvs_get_blob

描述&#xff1a; nvs_get_blob(nvshandle,“nvconfig0”, phone_set_val.firststart,&phone_set_val_len); “nvconfig0"键名直接字符串没有问题&#xff0c;但是采用数组 nvconfig[12]{0}; memset(nvconfig,0,sizeof(nvconfig)); sprintf(nvconfig,”%s%d",“n…