elasticsearch操作(API方式)
说明:es操作索引库、文档,除了使用它们自带的命令外(参考:http://t.csdn.cn/4zpmi),在IDEA中可以添加相关的依赖,使用对应的API来操作。
准备工作
搭建一个SpringBoot项目,DAO使用的MyBatis-Plus,对数据库中的学生表进行操作。
pom.xml文件
<?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 http://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><version>2.3.10.RELEASE</version><relativePath/></parent><groupId>org.hzy</groupId><artifactId>es_essay_demo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><elasticsearch.version>7.12.1</elasticsearch.version></properties><dependencies><!--spring web依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--mybatis-plus依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency><!--数据库连接驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></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><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><!--FastJson--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.71</version></dependency><!--commons依赖--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency></dependencies>
</project>
在此之上,导入RestHighLevelClient依赖,并指定版本,不然会使用SpringBoot自带版本,依靠此依赖实现对ES的一系列操作。
<properties><elasticsearch.version>7.12.1</elasticsearch.version></properties><!--RestHighLevelClient依赖--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId></dependency>
编写与学生类相关的索引库DSL语句,注意这里特意把学生类中的创建日期、入学日期合并成一个joinInfo字段,后面添加文档时需要考虑到这点;
PUT /student
{"mappings": {"properties": {"id": {"type": "keyword"},"username":{"type": "keyword","copy_to": "all"},"password":{"type": "keyword","index": false},"name":{"type": "text","analyzer": "ik_max_word","copy_to": "all"},"gender":{"type": "keyword"},"image":{"type": "keyword"},"job":{"type": "integer"},"joinInfo":{"type": "keyword"},"updateTime":{"type": "keyword"},"all":{"type": "text","analyzer": "ik_max_word"}}}
}
将上面索引库的DSL语句,在IDEA中用一个常量来存储,以便后面使用,注意前面“PUT /student”需要去掉,只需要最外层花括号内的信息即可;
public class Constants {public static final String CREATE_INDEX_STRING = "{\n" +" \"mappings\": {\n" +" \"properties\": {\n" +" \"id\": {\n" +" \"type\": \"keyword\"\n" +" },\n" +" \n" +" \"username\":{\n" +" \"type\": \"keyword\",\n" +" \"copy_to\": \"all\"\n" +" },\n" +" \n" +" \"password\":{\n" +" \"type\": \"keyword\",\n" +" \"index\": false\n" +" },\n" +" \n" +" \"name\":{\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\",\n" +" \"copy_to\": \"all\"\n" +" },\n" +"\n" +" \"gender\":{\n" +" \"type\": \"keyword\"\n" +" },\n" +" \n" +" \"image\":{\n" +" \"type\": \"keyword\"\n" +" },\n" +" \n" +" \"job\":{\n" +" \"type\": \"integer\"\n" +" },\n" +"\t \n" +"\t \"joinInfo\":{\n" +"\t\t\"type\": \"keyword\"\n" +"\t },\n" +" \n" +" \"updateTime\":{\n" +" \"type\": \"keyword\"\n" +" },\n" +" \n" +" \n" +" \"all\":{\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\"\n" +" }\n" +" }\n" +" }\n" +"}";
}
索引库(index)操作
为了后面操作方便,把RestHighLevelClient的定义、创建、关闭放在方法外面,以下操作都是在测试类中实现;
/*** 定义连接*/private RestHighLevelClient client;/*** 初始化客户端*/@BeforeEachpublic void init(){client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.126.128:9200")));}/*** 关闭客户端* @throws IOException*/@AfterEachpublic void close() throws IOException {client.close();}
创建索引库
/*** 创建索引*/@Testpublic void addIndex() throws IOException {// 1.创建请求CreateIndexRequest createIndexRequest = new CreateIndexRequest("student");// 2.编写DSL语句createIndexRequest.source(CREATE_INDEX_STRING, XContentType.JSON);// 3.发起请求client.indices().create(createIndexRequest, RequestOptions.DEFAULT);}
执行成功
到ikbana上看下,索引库已经创建完成
获取索引库
/*** 获取索引库* @throws IOException*/@Testpublic void getIndex() throws IOException {// 1.创建请求GetIndexRequest getIndexRequest = new GetIndexRequest("student");// 2.发起请求boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);System.out.println("exists = " + exists);}
此方法返回结果为boolean类型,仅可知该索引库是否存在;
删除索引库
/*** 删除索引库* @throws IOException*/@Testpublic void deleteIndex() throws IOException {// 1. 创建请求DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("student");// 2. 发起请求client.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);}
删除索引库成功;
再次获取索引库,返回false;
小结
索引库没有修改操作
文档(document)操作
再提一次,文档操作等同于数据库的数据操作,即类比数据的CRUD操作;
新增文档
注意,因为数据库中查询到的记录与ES的文档的字段并不是一一对应的,需要再创建一个对象来进行拼凑;
(Student类)
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;import java.io.Serializable;@Data
@TableName("tb_student")
public class Student implements Serializable {private Integer id;private String username;private String password;private String name;private Integer gender;private String image;private Integer job;private String entryDate;private String createTime;private String updateTime;
}
(StudentDoc类,与ES文档一一对应)
import lombok.Data;
import lombok.NoArgsConstructor;import java.io.Serializable;@Data
@NoArgsConstructor
public class StudentDoc implements Serializable {private Integer id;private String username;private String password;private String name;private Integer gender;private String image;private Integer job;private String joinInfo;private String updateTime;public StudentDoc(Student student) {this.id = student.getId();this.username = student.getUsername();this.password = student.getPassword();this.name = student.getName();this.gender = student.getGender();this.image = student.getImage();this.job = student.getJob();this.joinInfo = "[创建日期:" + student.getCreateTime() + "], [加入日期:" + student.getEntryDate() +"]";this.updateTime = student.getUpdateTime();}
}
/*** 新增文档(数据来自数据库,然后新增到ES)*/@Testpublic void addDoc() throws IOException {// 1.查询数据(ID为1的记录)Student student = studentService.getById(1);// 1.1 拼凑文档StudentDoc studentDoc = new StudentDoc(student);// 2.创建请求IndexRequest request = new IndexRequest("student").id(student.getId().toString());// 3.编写DSL语句request.source(JSON.toJSONString(studentDoc),XContentType.JSON);// 4.发送请求client.index(request,RequestOptions.DEFAULT);}
执行完成;
查看kibana平台,输入命令,可以查到对应的文档,说明新增文档成功;
查询文档
/*** 查询文档*/@Testpublic void getDoc() throws IOException {// 1.创建请求,查询ID为1的文档GetRequest request = new GetRequest("student").id("1");// 2.发送请求GetResponse response = client.get(request, RequestOptions.DEFAULT);// 3.获取返回值String json = response.getSourceAsString();// 4.解析返回值为java对象StudentDoc studentDoc = JSON.parseObject(json, StudentDoc.class);System.out.println("studentDoc = " + studentDoc);}
查询完成;
删除文档
/*** 删除文档*/@Testpublic void delDoc() throws IOException {// 1.创建请求,删除ID为1的文档DeleteRequest request = new DeleteRequest("student").id("1");// 2.发起请求client.delete(request, RequestOptions.DEFAULT);}
执行完成;
再次查询,结果为null(注意,并不会报错);
更新文档
更新文档由两种方式,第一种是全局更新,其实也就是新增文档,代码是一样的,第二种是局部更新,代码如下:
/*** 更新文档(方式二:局部更新)*/@Testpublic void updateDoc() throws IOException {// 1.创建请求,修改ID为1的文档UpdateRequest request = new UpdateRequest("student","1");// 2.指定要修改的字段request.doc("name","徐志摩","username","xuzhimo");// 3.发送请求client.update(request,RequestOptions.DEFAULT);}
执行完成;
再次查找ID为1的文档,可以看到文档已更新;
批量导入文档
批量将数据库中的对象数据,导入到ES上;
/*** 批量导入文档(数据从数据库中查询获取)*/@Testpublic void addDocs() throws IOException {// 1.获取所有学生的数据List<Student> students = studentService.list();// 2.创建Bulk请求BulkRequest bulkRequest = new BulkRequest();// 3.添加数据到Bulk中for (Student student : students) {// 3.1 创建Doc对象StudentDoc studentDoc = new StudentDoc(student);// 3.2 创建新增文档请求并将Doc对象放入bulkRequest.add(new IndexRequest("student").id(studentDoc.getId().toString()).source(JSON.toJSONString(studentDoc),XContentType.JSON));}// 4.发送请求client.bulk(bulkRequest,RequestOptions.DEFAULT);}
执行完成,没有报错;
随便查找两条记录,可以看到都已经添加了进来;
总结
对于索引库的操作,请求是XxxIndexRequest(“索引库名”),创建是Create,删除是Delete,获取是Get(发起请求,方法名是exists);
对于文档的操作,请求是XxxRequest(“索引库名”,“ID”),新增是Index,删除是Delete,查询是Get,修改是Update,另外还有个批量的操作,是BulkRequest;
相关文章:

elasticsearch操作(API方式)
说明:es操作索引库、文档,除了使用它们自带的命令外(参考:http://t.csdn.cn/4zpmi),在IDEA中可以添加相关的依赖,使用对应的API来操作。 准备工作 搭建一个SpringBoot项目,DAO使用…...

Vue2.0 使用 echarts
目录 1. 配置 渲染2. 数据渲染 1. 配置 渲染 安装 echarts 依赖 npm install echarts -Smain.js,引入 echarts import * as echarts from echarts// 在import的后面,echarts的前面加一个 * as Vue.prototype.$echarts echarts从 echarts 官网直接复制…...
企业微信,阿里钉钉告警群机器人
链接:如何通过企业微信群接收报警通知_云监控-阿里云帮助中心...

linux下的tomcat
springboot项目端口是8080,部署到linux运行之后,为什么能检测到tomcat 手动安装tomcat,以下是在 Linux 系统上安装 Tomcat 的步骤: 下载 Tomcat 安装包。您可以从 Tomcat 官方网站(https://tomcat.apache.org/ ↗&…...
Vue源码学习 - new Vue初始化都做了什么?
目录 前言一、创建一个 Vue 实例二、找到 Vue 构造函数三、源码分析 - Vue.prototype._init四、源码分析 - 调用 $mount 方法,进入挂载阶段五、总结 前言 使用Vue也有一段时间了,最近去阅读了Vue的源码,想总结分享下学到的新东西。 如果觉得…...

新零售数字化商业模式如何建立?新零售数字化营销怎么做?
随着零售行业增速放缓、用户消费结构升级,企业需要需求新的价值增长点进行转型升级,从而为消费者提供更为多元化的消费需求、提升自己的消费体验。在大数据、物联网、5G及区块链等技术兴起的背景下,数字化新零售系统应运而生。 开利网络认为&…...

C++语法(26)--- 特殊类设计
C语法(25)--- 异常与智能指针_哈里沃克的博客-CSDN博客https://blog.csdn.net/m0_63488627/article/details/131537799?spm1001.2014.3001.5501 目录 1.特殊类设计 1.设计一个类,不能被拷贝 C98 C11 2.设计一个类,只能在堆上…...

YAML+PyYAML笔记 2 | YAML缩进、分离、注释简单使用
2 | YAML缩进、分离、注释简单使用 1 简介2 缩进3 分离4 多行文本4.1 折叠块4.2 字面块4.3 引用块 5 注释5.1 行内注释5.2 块注释5.3 完美注释示例 1 简介 YAML 不是一种标记语言,而是一种数据格式;使用缩进和分离来表示数据结构,不需要使用…...

Array(20) 和 Array.apply(null, {length: 20})
1.Array(20) 其结果是: 创建了一个长度为20,但元素均为 empty 的数组。 2.Array.apply(null, { length: 20 }) 其结果是: 创建了一个长度为20,但元素均为 undefined 的数组。 3.异同 3.1相同 console.log(arr1[0] arr2[0]) /…...

Mind+积木编程控制小水泵给宠物喂水
前期用scratch,带着小朋友做了大鱼吃小鱼、桌面弹球、小学生计算器3个作品,小朋友收获不小。关键是小家伙感兴趣,做出来后给家人炫耀了一圈后,兴趣大增,嚷嚷着要做更好玩的。 最近,娃妈从抖音上买了个小猫喝…...

【Linux从入门到精通】进程的控制(进程替换)
本篇文章会对进程替换进行讲解。希望本篇文章会对你有所帮助 文章目录 一、进程替换概念 二、进程替换函数 2、1 execl 2、2 execlp 2、3 execv 2、3 execle 2、4 execve 三、总结 🙋♂️ 作者:Ggggggtm 🙋♂️ 👀 专栏&…...

rancher平台上强制删除pod服务操作
背景: 在日常paas平台运维工作中需要对rancher平台进行巡检的工作,在巡检时发现在rancher管理界面无法删除异常的pod服务, 处理: 像这样的情况就是k8s集群的pod无法通过默认的方式去删除掉pod服务,这时候只能是手工强制…...

【Docker】Docker的通信安全
Docker的通信安全 前言一、Docker 容器与虚拟机的区别1. 隔离与共享2. 性能与损耗 二、Docker 存在的安全问题1. Docker 自身漏洞2. Docker 源码问题 三、Docker 架构缺陷与安全机制1. 容器之间的局域网攻击2. DDoS 攻击耗尽资源3. 有漏洞的系统调用4. 共享 root 用户权限 四、…...
c# 函数中可选参数太多,想设置最后一个参数,又不想修改前面默认参数
C#中,你可以使用命名参数来指定你想要设置的可选参数,而保留其他参数的默认值不变。通过使用命名参数,你可以根据需要选择要为哪些参数提供值,而无需按照它们在函数签名中的顺序提供参数值。 以下是一个示例,演示如何…...
openvino资料(1)
1、c++ - OpenVino model outputs zeroes - Stack Overflow 2、https://chinait-intel.oss-cn-beijing.aliyuncs.com/OpenVINO/Ubuntu20.04%E7%8E%AF%E5%A2%83%E4%B8%8B%E4%BD%BF%E7%94%A8OpenVINO%E9%83%A8%E7%BD%B2BiSeNetV2%E6%A8%A1%E5%9E%8B.pdf 3、c++ - How to cre...

第71篇:某银行外网打点到内网核心区红队评估复盘
Part1 前言 大家好,我是ABC_123。本期分享一篇ABC_123曾经做的针对一家银行的红队评估项目,持续时间两周,难度非常大,但是最终打到了银行核心业务区,今天就复盘一下全过程,希望红蓝双方都能得到一些启示&a…...
网络安全 Day21-数据库知识
数据库知识 1. 什么是数据库2. 为什么需要数据库(分类不清晰)3. 数据库的种类3.1 关系型数据库3.2 NOSQL 数据库3.3 new sql (国产数据库)分布式数据库3.4 云数据库 4. mysql 关系型数据库5. 安装mariadb6. 为mariadb设置密码7. M…...

python测试开发面试常考题:装饰器
目录 简介 应用 第一类对象 装饰器 描述器descriptor 资料获取方法 简介 Python 装饰器是一个可调用的(函数、方法或类),它获得一个函数对象 func_in 作为输入,并返回另一函数对象 func_out。它用于扩展函数、方法或类的行为。 装饰器模式通常用…...

语音同声翻译软件让你不再为语言障碍困扰
从前有一个叫黄俊的小伙子,他有一个大梦想:环游世界!但是,他只会说中文,而去到外国又怎么跟当地人交流呢?为了实现自己的梦想,黄俊开始了寻找能帮他解决问题的捷径。这时,方娜向他介…...
又有一个手艺人震惊了B站用户
飞瓜数据(B站版)【热门视频榜】周榜显示,霸占全站视频流量第一的是来自UP主爱捣鼓的邢志磊发布的作品《我花了半年时间给猫做了个房子》。 视频在一周时间内新增播放1232.2万,新增点赞139.4万。 根据视频详细数据显示,…...
内存分配函数malloc kmalloc vmalloc
内存分配函数malloc kmalloc vmalloc malloc实现步骤: 1)请求大小调整:首先,malloc 需要调整用户请求的大小,以适应内部数据结构(例如,可能需要存储额外的元数据)。通常,这包括对齐调整,确保分配的内存地址满足特定硬件要求(如对齐到8字节或16字节边界)。 2)空闲…...

基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真
目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销,平衡网络负载,延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...

边缘计算医疗风险自查APP开发方案
核心目标:在便携设备(智能手表/家用检测仪)部署轻量化疾病预测模型,实现低延迟、隐私安全的实时健康风险评估。 一、技术架构设计 #mermaid-svg-iuNaeeLK2YoFKfao {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg…...

学校招生小程序源码介绍
基于ThinkPHPFastAdminUniApp开发的学校招生小程序源码,专为学校招生场景量身打造,功能实用且操作便捷。 从技术架构来看,ThinkPHP提供稳定可靠的后台服务,FastAdmin加速开发流程,UniApp则保障小程序在多端有良好的兼…...
生成 Git SSH 证书
🔑 1. 生成 SSH 密钥对 在终端(Windows 使用 Git Bash,Mac/Linux 使用 Terminal)执行命令: ssh-keygen -t rsa -b 4096 -C "your_emailexample.com" 参数说明: -t rsa&#x…...

SAP学习笔记 - 开发26 - 前端Fiori开发 OData V2 和 V4 的差异 (Deepseek整理)
上一章用到了V2 的概念,其实 Fiori当中还有 V4,咱们这一章来总结一下 V2 和 V4。 SAP学习笔记 - 开发25 - 前端Fiori开发 Remote OData Service(使用远端Odata服务),代理中间件(ui5-middleware-simpleproxy)-CSDN博客…...

论文阅读:LLM4Drive: A Survey of Large Language Models for Autonomous Driving
地址:LLM4Drive: A Survey of Large Language Models for Autonomous Driving 摘要翻译 自动驾驶技术作为推动交通和城市出行变革的催化剂,正从基于规则的系统向数据驱动策略转变。传统的模块化系统受限于级联模块间的累积误差和缺乏灵活性的预设规则。…...
用鸿蒙HarmonyOS5实现中国象棋小游戏的过程
下面是一个基于鸿蒙OS (HarmonyOS) 的中国象棋小游戏的实现代码。这个实现使用Java语言和鸿蒙的Ability框架。 1. 项目结构 /src/main/java/com/example/chinesechess/├── MainAbilitySlice.java // 主界面逻辑├── ChessView.java // 游戏视图和逻辑├──…...
API网关Kong的鉴权与限流:高并发场景下的核心实践
🔥「炎码工坊」技术弹药已装填! 点击关注 → 解锁工业级干货【工具实测|项目避坑|源码燃烧指南】 引言 在微服务架构中,API网关承担着流量调度、安全防护和协议转换的核心职责。作为云原生时代的代表性网关,Kong凭借其插件化架构…...
字符串哈希+KMP
P10468 兔子与兔子 #include<bits/stdc.h> using namespace std; typedef unsigned long long ull; const int N 1000010; ull a[N], pw[N]; int n; ull gethash(int l, int r){return a[r] - a[l - 1] * pw[r - l 1]; } signed main(){ios::sync_with_stdio(false), …...