SpringBoot 整合es(elasticsearch)使用elasticsearch-rest-high-level-client实现增删改
引入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency> <dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch的客户端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch依赖2.x的log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency> <!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
yml文件
#elasticsearch
esHostName: 192.168.1.25
esPort: 9200
ContentModel.java 根据自己的实际业务来
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors; /**
* es存放实体类
*/
@Data
@Accessors(chain = true)
@ToString
public class ContentModel { private static final long serialVersionUID = 6320548148250372657L; private Integer contentId; private String title; }
配置类
EsConfig.java
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; /**
* @author yvioo。
*/
@Configuration
public class EsConfig { @Value("${esHostName}")
private String esHostName; @Value("${esPort}")
private Integer esPort; public static final RequestOptions COMMON_OPTIONS; static {
RequestOptions.Builder builder=RequestOptions.DEFAULT.toBuilder();
COMMON_OPTIONS=builder.build();
} @Bean
public RestHighLevelClient esRestClient(){
RestClientBuilder builder = RestClient.builder(new HttpHost(esHostName, esPort, "http"));
RestHighLevelClient client=new RestHighLevelClient(builder);
return client;
}
}
常量
EsConstant.java 可以不用
/**
* @author yvioo。
*/
public class EsConstant { public static final String CONTENT_INDEX="索引名称"; public static final String CONTENT_TYPE="类型"; }
工具类
EsService.java
import com.alibaba.fastjson.JSON;
import com.example.es.elasticsearch.entity.ContentModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors; /**
* es操作类
*
* @author 洪。
*/
@Slf4j
@Service
public class EsService { @Resource
private RestHighLevelClient restHighLevelClient; /**
* 批量插入文档数据
* @return 返回true 表示有错误
*/
public boolean batchEsContent(List<ContentModel> contentModelList) throws IOException { BulkRequest bulkRequest = new BulkRequest();
List<Integer> delIds=new LinkedList<>(); for (ContentModel model : contentModelList) {
IndexRequest indexRequest = new IndexRequest(EsConstant.CONTENT_INDEX).type(EsConstant.CONTENT_TYPE);
indexRequest.id(model.getContentId().toString());
String s = JSON.toJSONString(model);
indexRequest.source(s, XContentType.JSON);
bulkRequest.add(indexRequest); } BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS); List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
return item.getId();
}).collect(Collectors.toList());
log.error("内容索引生成:{}", collect);
return bulk.hasFailures();
} /**
* 判断是否存在文档数据
*
* @param id 索引的ID
* @return
* @throws IOException
*/
public boolean existIndex(Integer id) throws IOException {
GetRequest getRequest = new GetRequest(
EsConstant.CONTENT_INDEX,
id.toString());
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
return restHighLevelClient.exists(getRequest, EsConfig.COMMON_OPTIONS);
} /**
* 删除文档数据
* @param id
* @return
* @throws IOException
*/
public boolean deleteIndex(Integer id) throws IOException {
DeleteRequest request = new DeleteRequest(
EsConstant.CONTENT_INDEX,
id.toString());
DeleteResponse deleteResponse = restHighLevelClient.delete(
request, EsConfig.COMMON_OPTIONS);
if (deleteResponse.status().getStatus()== RestStatus.OK.getStatus()){
return true;
}
return false;
} /**
* 批量删除索引
* @param ids
* @return 返回true 表示有错误
* @throws IOException
*/
public boolean deleteBatchIndex(List<Integer> ids) throws IOException { // 批量删除数据
BulkRequest request = new BulkRequest(); ids.forEach(s->{
request.add(new DeleteRequest().index(EsConstant.CONTENT_INDEX).type(EsConstant.CONTENT_TYPE).id(s.toString()));
}); BulkResponse response = restHighLevelClient.bulk(request, EsConfig.COMMON_OPTIONS);
return response.hasFailures();
} /**
* 更新文档数据
* @param contentModel
* @return
* @throws IOException
*/
public boolean updateIndex(ContentModel contentModel) throws IOException {
// 修改数据
UpdateRequest request = new UpdateRequest();
request.index(EsConstant.CONTENT_INDEX).id(contentModel.getContentId().toString());
String s = JSON.toJSONString(contentModel);
request.doc(s, XContentType.JSON); UpdateResponse updateResponse = restHighLevelClient.update(request, EsConfig.COMMON_OPTIONS);
if (updateResponse.status().getStatus()== RestStatus.OK.getStatus()){
return true;
}
return false;
} }
使用直接注入 EsService 然后调用里面的方法即可
由于每种业务查询的写法都不一定,没有通用性 所以这里没有提供查询的方法
SpringBoot 整合es(elasticsearch)使用elasticsearch-rest-high-level-client实现增删改的更多相关文章
- springboot整合es客户端操作elasticsearch(五)
springboot整合es客户端操作elasticsearch的总结: 客户端可以进行可以对所有文档进行查询,就是不加任何条件: SearchRequest searchRequest = new ...
- springboot整合es客户端操作elasticsearch(二)
在上章节中整合elasticsearch客户端出现版本问题进行了处理,这章来进行springboot整合得操作 环境:elaticsearch6.2.1,springboot 2.1.8 客户端版本采 ...
- springboot整合es客户端操作elasticsearch(四)
对文档查询,在实际开发中,对文档的查询也是偏多的,记得之前在mou快递公司,做了一套事实的揽件数据操作,就是通过这个来存储数据的,由于一天的数据最少拥有3500万数据 所以是比较多的,而且还要求查询速 ...
- springboot整合es客户端操作elasticsearch(三)
继续上个随笔: 那么我们只需要修改controller中文件就可以完成相关操作 本次主要是对文档得操作: 更新文档: package com.cxy.elasticsearch.controller; ...
- SpringBoot整合ES+Kibana
前言:最近在写一个HTTP代理服务器,记录日志使用的是ES,所以涉及到SpringBoot和ES的整合,整合完毕后又涉及到数据可视化分析,所以使用了Kibana进行管理,有些坑,需要记录一下 Spri ...
- ElasticSearch(三)springboot整合ES
最基础的整合: 一.maven依赖 <parent> <groupId>org.springframework.boot</groupId> <artifac ...
- 2.SSM整合_多表_一对一或多对一的增删改查
一对一和多对一配置一样,这里就放到一起. 1.配置文件跟上一章一样,这里就不多写了,主要是Mapper映射文件 多 接口 public interface NewsMapper { public vo ...
- SpringBoot+MyBatis中自动根据@Table注解和@Column注解生成增删改查逻辑
习惯使用jpa操作对象的方式,现在用mybatis有点不习惯. 其实是懒得写SQL,增删改查那么简单的事情你帮我做了呗,mybatis:NO. 没办法,自己搞喽! 这里主要是实现了通过代码自动生成my ...
- Springboot+Mybatis+Clickhouse+jsp 搭建单体应用项目(三)(添加增删改查)
一.添加增加接口 @ApiResponses(value = { @ApiResponse(code = 200, message = "接口返回成功状态"), @ApiRespo ...
随机推荐
- CF1368F Lamps on a Circle
思考我们一定有最后一个状态是空着的灯是按照一个间隔\(k\) 只要将原来\(n\)个灯,每\(k\)个分一组,强制将最后一盏灯不选,并且第n盏灯不选,需要注意的是某一组一定会被第二个人全部关掉,那么可 ...
- Matlab 代码注释
Matlab 代码注释 一直在找类似doxygen一样将程序注释发表成手册的方法,现在发现,Matlab的publish功能自己就能做到. Publish 简介 并非所有注释都能作为文本进行输出,MA ...
- 【GS文献】植物全基因组选择育种技术原理与研究进展
目录 1. 优势杂交育种预测 2. GS育种原理与模型算法 岭回归和LASSO回归 贝叶斯方法 GBLUP和RRBLUP 偏最小二乘法 支持向量机/支持向量回归 其他方法 3. 模型预测能力验证 4. ...
- linux—查看所有的账号以及管理账号
用过Linux系统的人都知道,Linux系统查看用户不是会Windows那样,鼠标右键看我的电脑属性,然后看计算机用户和组即可. 那么Linux操作系统里查看所有用户该怎么办呢?用命令.其实用命令就能 ...
- excel-合并多个Excel文件--VBA合并当前目录下所有Excel工作簿中的所有工作表
在网上找EXCEL多文件合并的方法,思路: 一.Linux 或者window+cmder,直接用命令行cat合并EXCEL文件,但是,需要安装辅助东西才能直接处理(也许也不可以,但是,可以用文件格式转 ...
- kubernetes部署 etcd 集群
本文档介绍部署一个三节点高可用 etcd 集群的步骤: etcd 集群各节点的名称和 IP 如下: kube-node0:192.168.111.10kube-node1:192.168.111.11 ...
- 【题解】洛谷P1001 A+B Problem
第一篇博客,献给2020年的残夏. 静听8月的热情与安宁,在竞赛中的时光如白驹过隙. 也不惧未知的风雨,努力向着既往的通途. 题目地址 https://www.luogu.com.cn/problem ...
- HDC2021技术分论坛:异构组网如何解决共享资源冲突?
作者:lijie,HarmonyOS软总线领域专家 相信大家对HarmonyOS的"超级终端"比较熟悉了.那么,您知道超级终端场景下的多种设备在不同环境下是如何组成一个网络的吗?这 ...
- DBeaver客户端工具连接Hive
目录 介绍 下载安装 相关配置 1.填写主机名 2.配置驱动 简单使用 主题设置 字体背景色 介绍 在hive命令行beeline中写一些很长的查询语句不是很方便,急需一个hive的客户端界面工具 D ...
- Dubbo服务调用超时
服务降级的发生,其实是由于消费者调用服务超时引起的,即从发出调用请求到获取到提供者的响应结果这个时间超出了设定的时限.默认服务调用超时时限为1秒.可以在消费者端与提供者端设置超时时限. 一.创建提供者 ...