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 框架(库)jQueryPrototypeMooTools其他框架CDN -内容分发网络引用 jQuery使用框架JavaScript 库 JavaScript 库 - jQuery、Prototype、MooTools。 JavaScript 框架(库) JavaScript 高级程序设计…...
云解析DNS为什么要配置默认线路?
传统解析技术不会判断访客IP,而是会随机选择一个IP返回给访问者,这样就有可能造成移动用户访问电信服务器IP,北京用户访问深圳服务器IP这种跨域跨网访问的情况,产生非常大的延迟,带来很不好的访问体验。 而云解析DNS会…...
Linux命令之awk
awk是一个有强大的文本格式化能力的linux命令,早期是在Unix上实现的,linux后来也可以使用了,我们在Linux上使用的awk是gawk(GNU awk的意思) 语法 awk [option] 模式{动作} file option表示awk的可选参数,可…...
实战-缓存数据一致+binlog初始+cannel监听+数据迁移,数据一致性架构设计
前言 一. 解决缓存不命中(高并发操作击穿打挂DB的风险) 当并发量打的时候,当我们的缓存过期时,就算到数据库的比例偏小的时候,我们的请求时比较大的。那也会存在数据库崩掉的情况。解决方案想法如下(总体…...
nginx配置中proxy_pass反向代理502的bug
记录一个坑人的bug, 我今天在一台新的liunx上运行nginx来进行反向代理时候,发现怎么测都是502 我把配置全部删了从头开始配置,发现80端口正常,80端口index.html正常,反向代理转向http://127.0.0.1/也正常,…...
JavaScript 两种方案打开文件对话框
JavaScript 两种方案打开文件对话框 文章目录JavaScript 两种方案打开文件对话框一、文件对话框二、传统方案表单元素🌈三、文件系统访问API💦四、更进一步使用六、代码仓库🌐七、参考资料💘七、推荐博文🍗一、文件对话…...
Pycharm远程服务器常见问题
2023年02月23日 问题描述:Pycharm远程服务器跑代码时,不小心把Pycharm关掉了,但服务器代码还在运行? 解决办法:kill进程 先用watch -n 0.5 nvidia_smi查看进程,然后kill -9 <进程> 1、nvidia-smi…...
内容团队如何快速出稿
对于内容团队而言,每个内容选题就相当于一个小项目,它们并非简单的线性工作流,相反其复杂程度不亚于一个小型工厂。一个内容选题会涉及内容形式,选题类型等多个变量,这些变量因素组合起来就是十几种不同类型的工作流。…...
es-08索引的批量操作
索引的批量操作 批量查询和批量增删改 批量查询 GET /_mget#批量查询 GET product/_search GET /_mget {"docs": [{"_index": "product","_id": 2},{"_index": "product","_id": 3}] }GET product/_mge…...
诈金花的概率
游戏使用一副除去大小王的扑克牌,共4个花色52张牌。 1、豹子(AAA最大,222最小)。2、同花顺(AKQ最大,A23最小)。3、同花(AKQ最大,352最小)。4、顺子ÿ…...
ESP32设备驱动-MLX90393磁场传感器驱动
MLX90393磁场传感器驱动 文章目录 MLX90393磁场传感器驱动1、MLX90393介绍2、硬件准备3、软件准备4、驱动实现1、MLX90393介绍 MLX90393 磁场传感器可以在运行时重新编程为不同的模式和不同的设置。 该传感器使用 Melexis 专有的 Triaxis 技术提供与沿 XYZ 轴感应的磁通密度成…...
Java面试题-Spring框架
Spring框架 1. BeanFactory和ApplicationContext有何区别 BeanFactory是Spring最底层的接口,是IoC的核心,定义IoC的基本功能。 BeanFactory具有:延迟实例化的特性。在启动的时候,不会实例化Bean,只有有需要从容器…...
【计算机物理模拟】-力矩、转动惯量和角速度之间的关系
力矩和角速度之间的关系可以通过牛顿第二定律和角动量定理来描述。 牛顿第二定律表明,物体的加速度与作用在物体上的合力成正比,加速度的方向与合力的方向相同。而对于旋转运动的物体,其加速度可以表示为半径 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源码配置、测试: 配置usb_cam ROS功能包 配置kinect 前提 vim 、 cmake 、 git 、 gcc 、 g 这些一般都装了 主要是Pangolin 、 OpenCV 、 Eigen的安装 18.04建议Pangolin0.5 创建工作空间 我们在主目录下创建一个catkin_…...
MVP简单模型搭建【架构】
MVP简介 MVP是一种项目架构设计模式(说白了就是我们产品的一种设计方案) 其实MVP本质 就是将View和Model完全隔离,通过Presenter统一调度管理(Presenter扮演着中介的角色)传统的设计思路是我们直接跟房东谈࿰…...
若依ruoyi框架实现目录树与查询页面联动
目录1、业务场景2、前端api.js修改index.vue修改template修改script修改3、后端controllerserviceimpldomainentitytreeselect1、业务场景 后管页面实现目录数与查询页面的联动,类似若依框架用户管理页面。 2、前端 api.js修改 在原有的js文件里配置目录树的查…...
Laravel框架学习笔记——Laravel环境配置及安装(Ubuntu20.04为例)
目录引言1、安装Nginx2、安装PHP3、安装Composer4、搭建Laravel框架项目5、修改Nginx映射6、安装MySQL引言 好久没写博客了,因为个人需要, 所以要涉及到Laravel框架的学习,所以会出一系列的关于PHP的Laravel框架学习笔记,希望能够…...
【根据当天日期输出明天的日期(需对闰年做判定)。】2022-5-15
缘由根据当天日期输出明天的日期(需对闰年做判定)。日期类型结构体如下: struct data{ int year; int month; int day;};-编程语言-CSDN问答 struct mdata{ int year; int month; int day; }mdata; int 天数(int year, int month) {switch (month){case 1: case 3:…...
Linux链表操作全解析
Linux C语言链表深度解析与实战技巧 一、链表基础概念与内核链表优势1.1 为什么使用链表?1.2 Linux 内核链表与用户态链表的区别 二、内核链表结构与宏解析常用宏/函数 三、内核链表的优点四、用户态链表示例五、双向循环链表在内核中的实现优势5.1 插入效率5.2 安全…...
java调用dll出现unsatisfiedLinkError以及JNA和JNI的区别
UnsatisfiedLinkError 在对接硬件设备中,我们会遇到使用 java 调用 dll文件 的情况,此时大概率出现UnsatisfiedLinkError链接错误,原因可能有如下几种 类名错误包名错误方法名参数错误使用 JNI 协议调用,结果 dll 未实现 JNI 协…...
智能在线客服平台:数字化时代企业连接用户的 AI 中枢
随着互联网技术的飞速发展,消费者期望能够随时随地与企业进行交流。在线客服平台作为连接企业与客户的重要桥梁,不仅优化了客户体验,还提升了企业的服务效率和市场竞争力。本文将探讨在线客服平台的重要性、技术进展、实际应用,并…...
Spring Boot面试题精选汇总
🤟致敬读者 🟩感谢阅读🟦笑口常开🟪生日快乐⬛早点睡觉 📘博主相关 🟧博主信息🟨博客首页🟫专栏推荐🟥活动信息 文章目录 Spring Boot面试题精选汇总⚙️ **一、核心概…...
MySQL 8.0 OCP 英文题库解析(十三)
Oracle 为庆祝 MySQL 30 周年,截止到 2025.07.31 之前。所有人均可以免费考取原价245美元的MySQL OCP 认证。 从今天开始,将英文题库免费公布出来,并进行解析,帮助大家在一个月之内轻松通过OCP认证。 本期公布试题111~120 试题1…...
成都鼎讯硬核科技!雷达目标与干扰模拟器,以卓越性能制胜电磁频谱战
在现代战争中,电磁频谱已成为继陆、海、空、天之后的 “第五维战场”,雷达作为电磁频谱领域的关键装备,其干扰与抗干扰能力的较量,直接影响着战争的胜负走向。由成都鼎讯科技匠心打造的雷达目标与干扰模拟器,凭借数字射…...
ios苹果系统,js 滑动屏幕、锚定无效
现象:window.addEventListener监听touch无效,划不动屏幕,但是代码逻辑都有执行到。 scrollIntoView也无效。 原因:这是因为 iOS 的触摸事件处理机制和 touch-action: none 的设置有关。ios有太多得交互动作,从而会影响…...
什么是Ansible Jinja2
理解 Ansible Jinja2 模板 Ansible 是一款功能强大的开源自动化工具,可让您无缝地管理和配置系统。Ansible 的一大亮点是它使用 Jinja2 模板,允许您根据变量数据动态生成文件、配置设置和脚本。本文将向您介绍 Ansible 中的 Jinja2 模板,并通…...
20个超级好用的 CSS 动画库
分享 20 个最佳 CSS 动画库。 它们中的大多数将生成纯 CSS 代码,而不需要任何外部库。 1.Animate.css 一个开箱即用型的跨浏览器动画库,可供你在项目中使用。 2.Magic Animations CSS3 一组简单的动画,可以包含在你的网页或应用项目中。 3.An…...
