引入依赖

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. <optional>true</optional>
  5. </dependency>
  6.  
  7. <dependency>
  8. <groupId>org.elasticsearch</groupId>
  9. <artifactId>elasticsearch</artifactId>
  10. <version>7.8.0</version>
  11. </dependency>
  12. <!-- elasticsearch的客户端 -->
  13. <dependency>
  14. <groupId>org.elasticsearch.client</groupId>
  15. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  16. <version>7.8.0</version>
  17. </dependency>
  18. <!-- elasticsearch依赖2.x的log4j -->
  19. <dependency>
  20. <groupId>org.apache.logging.log4j</groupId>
  21. <artifactId>log4j-api</artifactId>
  22. <version>2.8.2</version>
  23. </dependency>
  24.  
  25. <!-- 阿里JSON解析器 -->
  26. <dependency>
  27. <groupId>com.alibaba</groupId>
  28. <artifactId>fastjson</artifactId>
  29. <version>1.2.75</version>
  30. </dependency>

yml文件

  1. #elasticsearch
  2. esHostName: 192.168.1.25
  3. esPort: 9200
  1. ContentModel.java 根据自己的实际业务来
  1. import lombok.Data;
  2. import lombok.ToString;
  3. import lombok.experimental.Accessors;
  4.  
  5. /**
  6. * es存放实体类
  7. */
  8. @Data
  9. @Accessors(chain = true)
  10. @ToString
  11. public class ContentModel {
  12.  
  13. private static final long serialVersionUID = 6320548148250372657L;
  14.  
  15. private Integer contentId;
  16.  
  17. private String title;
  18.  
  19. }

配置类

EsConfig.java

  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.client.RequestOptions;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestClientBuilder;
  5. import org.elasticsearch.client.RestHighLevelClient;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9.  
  10. /**
  11. * @author yvioo。
  12. */
  13. @Configuration
  14. public class EsConfig {
  15.  
  16. @Value("${esHostName}")
  17. private String esHostName;
  18.  
  19. @Value("${esPort}")
  20. private Integer esPort;
  21.  
  22. public static final RequestOptions COMMON_OPTIONS;
  23.  
  24. static {
  25. RequestOptions.Builder builder=RequestOptions.DEFAULT.toBuilder();
  26. COMMON_OPTIONS=builder.build();
  27. }
  28.  
  29. @Bean
  30. public RestHighLevelClient esRestClient(){
  31. RestClientBuilder builder = RestClient.builder(new HttpHost(esHostName, esPort, "http"));
  32. RestHighLevelClient client=new RestHighLevelClient(builder);
  33. return client;
  34. }
  35. }

常量

EsConstant.java  可以不用

  1. /**
  2. * @author yvioo。
  3. */
  4. public class EsConstant {
  5.  
  6. public static final String CONTENT_INDEX="索引名称";
  7.  
  8. public static final String CONTENT_TYPE="类型";
  9.  
  10. }

工具类

EsService.java

  1. import com.alibaba.fastjson.JSON;
  2. import com.example.es.elasticsearch.entity.ContentModel;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.elasticsearch.action.bulk.BulkRequest;
  5. import org.elasticsearch.action.bulk.BulkResponse;
  6. import org.elasticsearch.action.delete.DeleteRequest;
  7. import org.elasticsearch.action.delete.DeleteResponse;
  8. import org.elasticsearch.action.get.GetRequest;
  9. import org.elasticsearch.action.index.IndexRequest;
  10. import org.elasticsearch.action.update.UpdateRequest;
  11. import org.elasticsearch.action.update.UpdateResponse;
  12. import org.elasticsearch.client.RestHighLevelClient;
  13. import org.elasticsearch.common.xcontent.XContentType;
  14. import org.elasticsearch.rest.RestStatus;
  15. import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
  16. import org.springframework.stereotype.Service;
  17.  
  18. import javax.annotation.Resource;
  19. import java.io.IOException;
  20. import java.util.*;
  21. import java.util.stream.Collectors;
  22.  
  23. /**
  24. * es操作类
  25. *
  26. * @author 洪。
  27. */
  28. @Slf4j
  29. @Service
  30. public class EsService {
  31.  
  32. @Resource
  33. private RestHighLevelClient restHighLevelClient;
  34.  
  35. /**
  36. * 批量插入文档数据
  37. * @return 返回true 表示有错误
  38. */
  39. public boolean batchEsContent(List<ContentModel> contentModelList) throws IOException {
  40.  
  41. BulkRequest bulkRequest = new BulkRequest();
  42. List<Integer> delIds=new LinkedList<>();
  43.  
  44. for (ContentModel model : contentModelList) {
  45. IndexRequest indexRequest = new IndexRequest(EsConstant.CONTENT_INDEX).type(EsConstant.CONTENT_TYPE);
  46. indexRequest.id(model.getContentId().toString());
  47. String s = JSON.toJSONString(model);
  48. indexRequest.source(s, XContentType.JSON);
  49. bulkRequest.add(indexRequest);
  50.  
  51. }
  52.  
  53. BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
  54.  
  55. List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
  56. return item.getId();
  57. }).collect(Collectors.toList());
  58. log.error("内容索引生成:{}", collect);
  59. return bulk.hasFailures();
  60. }
  61.  
  62. /**
  63. * 判断是否存在文档数据
  64. *
  65. * @param id 索引的ID
  66. * @return
  67. * @throws IOException
  68. */
  69. public boolean existIndex(Integer id) throws IOException {
  70. GetRequest getRequest = new GetRequest(
  71. EsConstant.CONTENT_INDEX,
  72. id.toString());
  73. getRequest.fetchSourceContext(new FetchSourceContext(false));
  74. getRequest.storedFields("_none_");
  75. return restHighLevelClient.exists(getRequest, EsConfig.COMMON_OPTIONS);
  76. }
  77.  
  78. /**
  79. * 删除文档数据
  80. * @param id
  81. * @return
  82. * @throws IOException
  83. */
  84. public boolean deleteIndex(Integer id) throws IOException {
  85. DeleteRequest request = new DeleteRequest(
  86. EsConstant.CONTENT_INDEX,
  87. id.toString());
  88. DeleteResponse deleteResponse = restHighLevelClient.delete(
  89. request, EsConfig.COMMON_OPTIONS);
  90. if (deleteResponse.status().getStatus()== RestStatus.OK.getStatus()){
  91. return true;
  92. }
  93. return false;
  94. }
  95.  
  96. /**
  97. * 批量删除索引
  98. * @param ids
  99. * @return 返回true 表示有错误
  100. * @throws IOException
  101. */
  102. public boolean deleteBatchIndex(List<Integer> ids) throws IOException {
  103.  
  104. // 批量删除数据
  105. BulkRequest request = new BulkRequest();
  106.  
  107. ids.forEach(s->{
  108. request.add(new DeleteRequest().index(EsConstant.CONTENT_INDEX).type(EsConstant.CONTENT_TYPE).id(s.toString()));
  109. });
  110.  
  111. BulkResponse response = restHighLevelClient.bulk(request, EsConfig.COMMON_OPTIONS);
  112. return response.hasFailures();
  113. }
  114.  
  115. /**
  116. * 更新文档数据
  117. * @param contentModel
  118. * @return
  119. * @throws IOException
  120. */
  121. public boolean updateIndex(ContentModel contentModel) throws IOException {
  122. // 修改数据
  123. UpdateRequest request = new UpdateRequest();
  124. request.index(EsConstant.CONTENT_INDEX).id(contentModel.getContentId().toString());
  125. String s = JSON.toJSONString(contentModel);
  126. request.doc(s, XContentType.JSON);
  127.  
  128. UpdateResponse updateResponse = restHighLevelClient.update(request, EsConfig.COMMON_OPTIONS);
  129. if (updateResponse.status().getStatus()== RestStatus.OK.getStatus()){
  130. return true;
  131. }
  132. return false;
  133. }
  134.  
  135. }

使用直接注入 EsService 然后调用里面的方法即可

由于每种业务查询的写法都不一定,没有通用性  所以这里没有提供查询的方法

SpringBoot 整合es(elasticsearch)使用elasticsearch-rest-high-level-client实现增删改的更多相关文章

  1. springboot整合es客户端操作elasticsearch(五)

    springboot整合es客户端操作elasticsearch的总结: 客户端可以进行可以对所有文档进行查询,就是不加任何条件: SearchRequest searchRequest = new ...

  2. springboot整合es客户端操作elasticsearch(二)

    在上章节中整合elasticsearch客户端出现版本问题进行了处理,这章来进行springboot整合得操作 环境:elaticsearch6.2.1,springboot 2.1.8 客户端版本采 ...

  3. springboot整合es客户端操作elasticsearch(四)

    对文档查询,在实际开发中,对文档的查询也是偏多的,记得之前在mou快递公司,做了一套事实的揽件数据操作,就是通过这个来存储数据的,由于一天的数据最少拥有3500万数据 所以是比较多的,而且还要求查询速 ...

  4. springboot整合es客户端操作elasticsearch(三)

    继续上个随笔: 那么我们只需要修改controller中文件就可以完成相关操作 本次主要是对文档得操作: 更新文档: package com.cxy.elasticsearch.controller; ...

  5. SpringBoot整合ES+Kibana

    前言:最近在写一个HTTP代理服务器,记录日志使用的是ES,所以涉及到SpringBoot和ES的整合,整合完毕后又涉及到数据可视化分析,所以使用了Kibana进行管理,有些坑,需要记录一下 Spri ...

  6. ElasticSearch(三)springboot整合ES

    最基础的整合: 一.maven依赖 <parent> <groupId>org.springframework.boot</groupId> <artifac ...

  7. 2.SSM整合_多表_一对一或多对一的增删改查

    一对一和多对一配置一样,这里就放到一起. 1.配置文件跟上一章一样,这里就不多写了,主要是Mapper映射文件 多 接口 public interface NewsMapper { public vo ...

  8. SpringBoot+MyBatis中自动根据@Table注解和@Column注解生成增删改查逻辑

    习惯使用jpa操作对象的方式,现在用mybatis有点不习惯. 其实是懒得写SQL,增删改查那么简单的事情你帮我做了呗,mybatis:NO. 没办法,自己搞喽! 这里主要是实现了通过代码自动生成my ...

  9. Springboot+Mybatis+Clickhouse+jsp 搭建单体应用项目(三)(添加增删改查)

    一.添加增加接口 @ApiResponses(value = { @ApiResponse(code = 200, message = "接口返回成功状态"), @ApiRespo ...

随机推荐

  1. 洛谷 P4272 - [CTSC2009]序列变换(堆)

    洛谷题面传送门 u1s1 在我完成这篇题解之前,全网总共两篇题解,一篇使用的平衡树,一篇使用的就是这篇题解讲解的这个做法,但特判掉了一个点,把特判去掉在 BZOJ 上会 WA 一个点. 两篇题解都异常 ...

  2. P2336 [SCOI2012]喵星球上的点名(SA+莫队)

    题面传送门 一道还算有点含金量的 SA 罢-- 首先按照套路我们把读入的所有字符串都粘在一起,中间用分隔符隔开并建出后缀数组出来. 我们考虑对于一个固定的字符串 \(s\),什么样的字符串 \(t\) ...

  3. Docker Nginx-Proxy 容器Nginx Proxy反向代理

    Docker Nginx-Proxy 容器Nginx Proxy反向代理   简单介绍 Docker容器的自动Nginx反向代理   dockerhub地址 https://hub.docker.co ...

  4. 深入浅出KMP

    前言:曾经有次在阿里的面试中遇到这个基础的问题,当时知道有这么回事,可是时间久了便 想不起来,可能是不怎么用到,基本调用库什么的,还有个是理解不深刻,不能得到show me the code 的程度, ...

  5. 前端2 — CSS — 更新完毕

    1.CSS是什么? 指:Cascading Style Sheet  --- 层叠样式表 CSS 即:美化网页( 在HTML不是说过W3C规定网页为三种标准嘛,结构层HTML已经玩了,而这个CSS就是 ...

  6. SpringCloud微服务实战——搭建企业级开发框架(三十):整合EasyExcel实现数据表格导入导出功能

      批量上传数据导入.数据统计分析导出,已经基本是系统必不可缺的一项功能,这里从性能和易用性方面考虑,集成EasyExcel.EasyExcel是一个基于Java的简单.省内存的读写Excel的开源项 ...

  7. 一文搞懂指标采集利器 Telegraf

    作者| 姜闻名 来源|尔达 Erda 公众号 ​ 导读:为了让大家更好的了解 MSP 中 APM 系统的设计实现,我们决定编写一个<详聊微服务观测>系列文章,深入 APM 系统的产品.架构 ...

  8. [源码解析] PyTorch分布式优化器(2)----数据并行优化器

    [源码解析] PyTorch分布式优化器(2)----数据并行优化器 目录 [源码解析] PyTorch分布式优化器(2)----数据并行优化器 0x00 摘要 0x01 前文回顾 0x02 DP 之 ...

  9. Flink(三)【核心编程】

    目录 一.Environment 二.Source 从集合读取数据 从文件读取数据 从kakfa读取数据(常用) 自定义数据源 三.Transform map Rich版本函数 flatMap key ...

  10. canal从mysql拉取数据,并以protobuf的格式往kafka中写数据

    大致思路: canal去mysql拉取数据,放在canal所在的节点上,并且自身对外提供一个tcp服务,我们只要写一个连接该服务的客户端,去拉取数据并且指定往kafka写数据的格式就能达到以proto ...