当前位置: 首页 > news >正文

ElasticSearch - SpringBoot整合ElasticSearch实现文档的增删改

文章目录

      • 1. ElasticSearch和kibana的安装和配置
      • 2. SpringBoot 项目环境搭建
      • 3. 创建索引
      • 4. 索引文档
      • 5. 更新文档
      • 6. 删除文档

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-your-data.html
https://www.elastic.co/guide/cn/elasticsearch/guide/current/_retrieving_a_document.html

1. ElasticSearch和kibana的安装和配置

① 下载地址:https://www.elastic.co/cn/downloads/past-releases/elasticsearch-7-4-2

② 修改elasticsearch.yml文件:

 cluster.name: my-applicationpath.data: D:/install/elasticsearch-7.4.2-windows-x86_64/elasticsearch-7.4.2/datapath.logs: D:/install/elasticsearch-7.4.2-windows-x86_64/elasticsearch-7.4.2/logs

③ 配置环境变量:D:\install\elasticsearch-7.4.2-windows-x86_64\elasticsearch-7.4.2\bin

④ 下载ik分词器:https://github.com/medcl/elasticsearch-analysis-ik/releases?after=v7.4.2

⑤ 解压ik分词器,必须解压到D:\install\elasticsearch-7.4.2-windows-x86_64\elasticsearch-7.4.2\plugins\ik目录下

⑥ 点击elasticsearch.bat启动elasticsearch服务,并访问:localhsot:9200

⑦ kibana下载地址:https://www.elastic.co/cn/downloads/past-releases/kibana-7-4-2

⑧ 修改kibana.yml文件(不必须):

 server.port: 5601server.host: "localhost"elasticsearch.hosts: ["http://localhost:9200"]i18n.locale: "zh-CN"

⑨ 点击kibana.bat启动kibana服务(一定要先启动es):

⑦ kibana下载地址:https://www.elastic.co/cn/downloads/past-releases/kibana-7-4-2

⑧ 修改kibana.yml文件(不必须):

 server.port: 5601server.host: "localhost"elasticsearch.hosts: ["http://localhost:9200"]i18n.locale: "zh-CN"

⑨ 点击kibana.bat启动kibana服务(一定要先启动es)

⑩ 访问localhost:5601

2. SpringBoot 项目环境搭建

1、创建项目:ElasticSearch和SpringBoot的版本一定要对应,否则会报各种错误

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><!-- 这里我的springboot的版本使用是2.3.2 --><version>2.3.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.xiao</groupId><artifactId>estest</artifactId><version>0.0.1-SNAPSHOT</version><name>estest</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><!-- 这里必须要填写,因为springboot2.3.2默认的elasticsearch版本为7.6.2,我们使用的是7.4.2,不更改会产生版本不兼容等问题 --><elasticsearch.version>7.4.2</elasticsearch.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 这里我使用的是elasticsearch的high-level-client 版本要和你的elasticsearch版本对应--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.4.2</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId><version>5.6.5</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.10</version><scope>provided</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2、创建一个配置类,用于配置Elasticsearch的集群信息:

@Configuration
public class ElasticSearchConfig {@Beanpublic RestHighLevelClient restHighLevelClient(){RestClientBuilder builder = RestClient.builder(new HttpHost("localhost",9200,"http"));RestHighLevelClient client = new RestHighLevelClient(builder);return client;}
}

3. 创建索引

1、在项目的resource/elasticsearch目录下创建一个文件mapping.json文件定义索引的映射:

{"properties": {"categoryId": {"type": "keyword"},"content": {"type": "text","analyzer": "ik_max_word","search_analyzer": "ik_smart"},"name": {"analyzer": "ik_max_word","search_analyzer": "ik_smart","type": "text"},"creator": {"type": "keyword"},"editor": {"type": "keyword"},"from": {"type": "keyword"},"id": {"type": "keyword"},"tags": {"type": "keyword"},"updateTime": {"type": "date","format": "yyyy-MM-dd HH:mm:ss||epoch_millis"},"createTime": {"type": "date","format": "yyyy-MM-dd HH:mm:ss||epoch_millis"}}
}

2、项目启动的时候判断knowledge索引是否存在并根据定义的映射创建该索引:

@Slf4j
@Service
public class ElasticSearchImpl {private static final String KNOWLEDGE_INDEX = "knowledge";@Autowiredprivate RestHighLevelClient restHighLevelClient;@PostConstructpublic void init(){try {// 查询索引GetIndexRequest request = new GetIndexRequest(KNOWLEDGE_INDEX);boolean exist = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);if (!exist) {CreateIndexRequest createIndexRequest = new CreateIndexRequest("knowledge");ClassPathResource mappingResource = new ClassPathResource("elasticsearch/mapping.json");byte[] bytes = FileCopyUtils.copyToByteArray(mappingResource.getInputStream());String json = new String(bytes, StandardCharsets.UTF_8);createIndexRequest.mapping(json, XContentType.JSON);restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);}} catch (IOException e) {log.error("failed to create index mapping:", e);throw new CommonException("elasticsearch.create.index.failed");}}
}

3、启动项目,在kibana客户端查看索引是否创建成功:

GET /knowledge/_search 
{"took" : 0,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 0,"relation" : "eq"},"max_score" : null,"hits" : [ ]}
}

说明索引添加成功。

4. 索引文档

1、定义一个映射对象:

@Data
public class Doc {private String id;private String name;private String content;private String creator;private String editor;private Date createTime;private Date updateTime;
}

2、索引文档:

@Slf4j
@Service
public class ElasticSearchImpl {private static final String KNOWLEDGE_INDEX = "knowledge";@Autowiredprivate RestHighLevelClient restHighLevelClient;public void saveDoc(Doc doc) throws JsonProcessingException {IndexRequest indexRequest = new IndexRequest("knowledge");indexRequest.id(doc.getId());// ES使用 json 文档代表了一个对象String jsonString = new JsonMapper().writeValueAsString(doc);indexRequest.source(jsonString, XContentType.JSON);// ElasticSearch是近实时搜索,刚索引的文档并不是立即对搜索可见,需要手动刷新indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);try {restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);} catch (IOException e) {log.error("failed to add document to elasticsearch,the doc is:{},the exception is {}", doc, e);throw new CommonException("elasticsearch.create.index.failed");}}
}

3、测试索引文档:

@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate ElasticSearchImpl elasticSearchImpl;@Testpublic void testSaveDoc(){// Elasticsearch 是面向文档的,意味着它存储整个对象或文档Doc doc = new Doc();doc.setId("1");doc.setName("茶花女");doc.setContent("这是一本非常好看的小说,有时间的小伙伴可以看一下");doc.setCreator("小仲马");doc.setEditor("小仲马");doc.setCreateTime(new Date());doc.setUpdateTime(new Date());elasticSearchImpl.saveDoc(doc);}
}

4、在kibana客户端查询索引中的文档:

GET /knowledge/_doc/1
{"_index" : "knowledge","_type" : "_doc","_id" : "1","_version" : 1,"_seq_no" : 0,"_primary_term" : 1,"found" : true,"_source" : {"id" : "1","name" : "茶花女","content" : "这是一本非常好看的小说,有时间的小伙伴可以看一下","creator" : "小仲马","editor" : "小仲马","createTime" : 1677229499680,"updateTime" : 1677229499680}
}

5. 更新文档

1、更新文档:

@Slf4j
@Service
public class ElasticSearchImpl {private static final String KNOWLEDGE_INDEX = "knowledge";@Autowiredprivate RestHighLevelClient restHighLevelClient;public void updateDoc(Doc doc) throws JsonProcessingException {UpdateRequest updateRequest = new UpdateRequest(KNOWLEDGE_INDEX, doc.getId());String jsonString = new JsonMapper().writeValueAsString(doc);updateRequest.doc(jsonString, XContentType.JSON);updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);try {restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);} catch (IOException e) {log.error("failed to update document to elasticsearch,the doc is:{},the exception is {}", doc, e);throw new CommonException("elasticsearch.create.index.failed");}}
}

2、测试更新文档:

@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate ElasticSearchImpl elasticSearchImpl;@Testpublic void testUpdateDoc() throws JsonProcessingException {// Elasticsearch 是面向文档的,意味着它存储整个对象或文档Doc doc = new Doc();doc.setId("1");doc.setName("茶花女");doc.setContent("这是一本非常好看的小说,有时间的小伙伴可以看一下");doc.setCreator("大仲马");doc.setEditor("大仲马");doc.setCreateTime(new Date());doc.setUpdateTime(new Date());elasticSearchImpl.saveDoc(doc);}
}

3、在kibana客户端查看索引中的文档:

{"_index" : "knowledge","_type" : "_doc","_id" : "1","_version" : 2,"_seq_no" : 1,"_primary_term" : 1,"found" : true,"_source" : {"id" : "1","name" : "茶花女","content" : "这是一本非常好看的小说,有时间的小伙伴可以看一下","creator" : "大仲马","editor" : "大仲马","createTime" : 1677229755142,"updateTime" : 1677229755142}
}

6. 删除文档

1、删除文档:

@Slf4j
@Service
public class ElasticSearchImpl {private static final String KNOWLEDGE_INDEX = "knowledge";@Autowiredprivate RestHighLevelClient restHighLevelClient;public void deleteDoc(Set<String> ids) {DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(KNOWLEDGE_INDEX);deleteByQueryRequest.setQuery(new TermsQueryBuilder("id", ids));deleteByQueryRequest.setRefresh(true);try {restHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);} catch (IOException e) {log.error("failed to delete the document in elasticsearch,the doc ids is:{},the exception is {}", ids, e);throw new CommonException("elasticsearch.create.index.failed");}}
}

2、测试删除文档:

@SpringBootTest
@RunWith(SpringRunner.class)
public class BeanLoadServiceTest {@Autowiredprivate ElasticSearchImpl elasticSearchImpl;@Testpublic void testDeleteDoc() throws JsonProcessingException {// Elasticsearch 是面向文档的,意味着它存储整个对象或文档List<String> list = Arrays.asList("1");elasticSearchImpl.deleteDoc(new HashSet<String>(list));}
}

3、在kibana客户端查看删除的文档:

GET /knowledge/_doc/1
{"_index" : "knowledge","_type" : "_doc","_id" : "1","found" : false
}

相关文章:

ElasticSearch - SpringBoot整合ElasticSearch实现文档的增删改

文章目录1. ElasticSearch和kibana的安装和配置2. SpringBoot 项目环境搭建3. 创建索引4. 索引文档5. 更新文档6. 删除文档https://www.elastic.co/guide/en/elasticsearch/reference/current/search-your-data.htmlhttps://www.elastic.co/guide/cn/elasticsearch/guide/curre…...

JavaScript 库

文章目录JavaScript 库JavaScript 框架&#xff08;库&#xff09;jQueryPrototypeMooTools其他框架CDN -内容分发网络引用 jQuery使用框架JavaScript 库 JavaScript 库 - jQuery、Prototype、MooTools。 JavaScript 框架&#xff08;库&#xff09; JavaScript 高级程序设计…...

云解析DNS为什么要配置默认线路?

传统解析技术不会判断访客IP&#xff0c;而是会随机选择一个IP返回给访问者&#xff0c;这样就有可能造成移动用户访问电信服务器IP&#xff0c;北京用户访问深圳服务器IP这种跨域跨网访问的情况&#xff0c;产生非常大的延迟&#xff0c;带来很不好的访问体验。 而云解析DNS会…...

Linux命令之awk

awk是一个有强大的文本格式化能力的linux命令&#xff0c;早期是在Unix上实现的&#xff0c;linux后来也可以使用了&#xff0c;我们在Linux上使用的awk是gawk&#xff08;GNU awk的意思&#xff09; 语法 awk [option] 模式{动作} file option表示awk的可选参数&#xff0c;可…...

实战-缓存数据一致+binlog初始+cannel监听+数据迁移,数据一致性架构设计

前言 一. 解决缓存不命中&#xff08;高并发操作击穿打挂DB的风险&#xff09; 当并发量打的时候&#xff0c;当我们的缓存过期时&#xff0c;就算到数据库的比例偏小的时候&#xff0c;我们的请求时比较大的。那也会存在数据库崩掉的情况。解决方案想法如下&#xff08;总体…...

nginx配置中proxy_pass反向代理502的bug

记录一个坑人的bug&#xff0c; 我今天在一台新的liunx上运行nginx来进行反向代理时候&#xff0c;发现怎么测都是502 我把配置全部删了从头开始配置&#xff0c;发现80端口正常&#xff0c;80端口index.html正常&#xff0c;反向代理转向http://127.0.0.1/也正常&#xff0c;…...

JavaScript 两种方案打开文件对话框

JavaScript 两种方案打开文件对话框 文章目录JavaScript 两种方案打开文件对话框一、文件对话框二、传统方案表单元素&#x1f308;三、文件系统访问API&#x1f4a6;四、更进一步使用六、代码仓库&#x1f310;七、参考资料&#x1f498;七、推荐博文&#x1f357;一、文件对话…...

Pycharm远程服务器常见问题

2023年02月23日 问题描述&#xff1a;Pycharm远程服务器跑代码时&#xff0c;不小心把Pycharm关掉了&#xff0c;但服务器代码还在运行&#xff1f; 解决办法&#xff1a;kill进程 先用watch -n 0.5 nvidia_smi查看进程&#xff0c;然后kill -9 <进程> 1、nvidia-smi…...

内容团队如何快速出稿

对于内容团队而言&#xff0c;每个内容选题就相当于一个小项目&#xff0c;它们并非简单的线性工作流&#xff0c;相反其复杂程度不亚于一个小型工厂。一个内容选题会涉及内容形式&#xff0c;选题类型等多个变量&#xff0c;这些变量因素组合起来就是十几种不同类型的工作流。…...

es-08索引的批量操作

索引的批量操作 批量查询和批量增删改 批量查询 GET /_mget#批量查询 GET product/_search GET /_mget {"docs": [{"_index": "product","_id": 2},{"_index": "product","_id": 3}] }GET product/_mge…...

诈金花的概率

游戏使用一副除去大小王的扑克牌&#xff0c;共4个花色52张牌。 1、豹子&#xff08;AAA最大&#xff0c;222最小&#xff09;。2、同花顺&#xff08;AKQ最大&#xff0c;A23最小&#xff09;。3、同花&#xff08;AKQ最大&#xff0c;352最小&#xff09;。4、顺子&#xff…...

ESP32设备驱动-MLX90393磁场传感器驱动

MLX90393磁场传感器驱动 文章目录 MLX90393磁场传感器驱动1、MLX90393介绍2、硬件准备3、软件准备4、驱动实现1、MLX90393介绍 MLX90393 磁场传感器可以在运行时重新编程为不同的模式和不同的设置。 该传感器使用 Melexis 专有的 Triaxis 技术提供与沿 XYZ 轴感应的磁通密度成…...

Java面试题-Spring框架

Spring框架 1. BeanFactory和ApplicationContext有何区别 BeanFactory是Spring最底层的接口&#xff0c;是IoC的核心&#xff0c;定义IoC的基本功能。 ​ BeanFactory具有&#xff1a;延迟实例化的特性。在启动的时候&#xff0c;不会实例化Bean&#xff0c;只有有需要从容器…...

【计算机物理模拟】-力矩、转动惯量和角速度之间的关系

力矩和角速度之间的关系可以通过牛顿第二定律和角动量定理来描述。 牛顿第二定律表明&#xff0c;物体的加速度与作用在物体上的合力成正比&#xff0c;加速度的方向与合力的方向相同。而对于旋转运动的物体&#xff0c;其加速度可以表示为半径 rrr 乘以角加速度 α\alphaα&a…...

async和await用法理解和快速上手 , 同步任务和异步任务顺序安排和轻松理解 , js代码执行顺序表面知道

学习关键语句 : async , await 用法 await 怎么使用 同步任务和异步任务 微任务和宏任务 js中代码执行顺序 写在前面 虽然说 async 和 await 是 Promise 的语法糖 , 但是用惯了Promise 的人(我) , 还真不能超快速使用上这个语法糖 , 所以赶紧写一篇文章出来让各位了解了解这个…...

Linux下java服务占用cpu过高如何处理

Linux下java服务占用cpu过高如何处理 top命令查看进程信息 top按下shiftp,按cpu使用率排行,可见进程1932占用最高,并且是一个java服务 使用jps命令确认java服务 [rootVM-16-16-centos ~]# jps 1011 Jps 9462 yuan_back-0.0.1-SNAPSHOT.jar 1932 spigot-1.18.jar查找异常进程中…...

ros下用kinectv2运行orbslam2

目录 前提 创建工作空间 orbslam2源码配置、测试&#xff1a; 配置usb_cam ROS功能包 配置kinect 前提 vim 、 cmake 、 git 、 gcc 、 g 这些一般都装了 主要是Pangolin 、 OpenCV 、 Eigen的安装 18.04建议Pangolin0.5 创建工作空间 我们在主目录下创建一个catkin_…...

MVP简单模型搭建【架构】

MVP简介 MVP是一种项目架构设计模式&#xff08;说白了就是我们产品的一种设计方案&#xff09; 其实MVP本质 就是将View和Model完全隔离&#xff0c;通过Presenter统一调度管理&#xff08;Presenter扮演着中介的角色&#xff09;传统的设计思路是我们直接跟房东谈&#xff0…...

若依ruoyi框架实现目录树与查询页面联动

目录1、业务场景2、前端api.js修改index.vue修改template修改script修改3、后端controllerserviceimpldomainentitytreeselect1、业务场景 后管页面实现目录数与查询页面的联动&#xff0c;类似若依框架用户管理页面。 2、前端 api.js修改 在原有的js文件里配置目录树的查…...

Laravel框架学习笔记——Laravel环境配置及安装(Ubuntu20.04为例)

目录引言1、安装Nginx2、安装PHP3、安装Composer4、搭建Laravel框架项目5、修改Nginx映射6、安装MySQL引言 好久没写博客了&#xff0c;因为个人需要&#xff0c; 所以要涉及到Laravel框架的学习&#xff0c;所以会出一系列的关于PHP的Laravel框架学习笔记&#xff0c;希望能够…...

浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)

✅ 一、ECS 服务配置 Dockerfile 确保监听 80 端口 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]或 EXPOSE 80 CMD ["python3", "-m", "http.server", "80"]任务定义&#xff08;Task Definition&…...

如何在看板中体现优先级变化

在看板中有效体现优先级变化的关键措施包括&#xff1a;采用颜色或标签标识优先级、设置任务排序规则、使用独立的优先级列或泳道、结合自动化规则同步优先级变化、建立定期的优先级审查流程。其中&#xff0c;设置任务排序规则尤其重要&#xff0c;因为它让看板视觉上直观地体…...

Linux云原生安全:零信任架构与机密计算

Linux云原生安全&#xff1a;零信任架构与机密计算 构建坚不可摧的云原生防御体系 引言&#xff1a;云原生安全的范式革命 随着云原生技术的普及&#xff0c;安全边界正在从传统的网络边界向工作负载内部转移。Gartner预测&#xff0c;到2025年&#xff0c;零信任架构将成为超…...

GitHub 趋势日报 (2025年06月08日)

&#x1f4ca; 由 TrendForge 系统生成 | &#x1f310; https://trendforge.devlive.org/ &#x1f310; 本日报中的项目描述已自动翻译为中文 &#x1f4c8; 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别 直接训练提示词嵌入向量的核心区别 您提到的代码: prompt_embedding = initial_embedding.clone().requires_grad_(True) optimizer = torch.optim.Adam([prompt_embedding...

成都鼎讯硬核科技!雷达目标与干扰模拟器,以卓越性能制胜电磁频谱战

在现代战争中&#xff0c;电磁频谱已成为继陆、海、空、天之后的 “第五维战场”&#xff0c;雷达作为电磁频谱领域的关键装备&#xff0c;其干扰与抗干扰能力的较量&#xff0c;直接影响着战争的胜负走向。由成都鼎讯科技匠心打造的雷达目标与干扰模拟器&#xff0c;凭借数字射…...

QT: `long long` 类型转换为 `QString` 2025.6.5

在 Qt 中&#xff0c;将 long long 类型转换为 QString 可以通过以下两种常用方法实现&#xff1a; 方法 1&#xff1a;使用 QString::number() 直接调用 QString 的静态方法 number()&#xff0c;将数值转换为字符串&#xff1a; long long value 1234567890123456789LL; …...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...

基于Java Swing的电子通讯录设计与实现:附系统托盘功能代码详解

JAVASQL电子通讯录带系统托盘 一、系统概述 本电子通讯录系统采用Java Swing开发桌面应用&#xff0c;结合SQLite数据库实现联系人管理功能&#xff0c;并集成系统托盘功能提升用户体验。系统支持联系人的增删改查、分组管理、搜索过滤等功能&#xff0c;同时可以最小化到系统…...

【若依】框架项目部署笔记

参考【SpringBoot】【Vue】项目部署_no main manifest attribute, in springboot-0.0.1-sn-CSDN博客 多一个redis安装 准备工作&#xff1a; 压缩包下载&#xff1a;http://download.redis.io/releases 1. 上传压缩包&#xff0c;并进入压缩包所在目录&#xff0c;解压到目标…...