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

RestClient操作索引库和文档

导入依赖:

        <dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.12.1</version></dependency>

导入依赖成功之后就可以开始我们的测试了!!!

RestClient操作索引库

创建RestClient

在测试方法中进行测试,首先我们需要创建一个RestHighLevelClient,使用@BeforeEach注解进行create,使用@AfterEach关闭链接。然后我们打印client

 	private RestHighLevelClient client;/*** BeforeEach注解是指,在执行其他测试方法之前,必须先执行一次该方法*/@BeforeEachvoid setUp() {client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://公网ip:9200")));}/*** AfterEach注解是指,在执行其他测试方法之后,必须先执行一次该方法*/@AfterEachvoid tearDown() throws IOException {client.close();}

在这里插入图片描述

新增索引库

  1. 创建Request对象
  2. 准备请求的参数:DSL语句
  3. 发生请求
    @Testvoid createHotelIndex() throws IOException {// 1. 创建Request对象CreateIndexRequest request = new CreateIndexRequest("user");// 2. 准备请求的参数:DSL语句request.source("{\n" +"  \"mappings\": {\n" +"    \"properties\": {\n" +"      \"id\": {\n" +"        \"type\": \"keyword\"\n" +"      },\n" +"      \"name\": {\n" +"        \"type\": \"text\",\n" +"        \"analyzer\": \"ik_max_word\"\n" +"      }\n" +"    }\n" +"  }\n" +"}", XContentType.JSON);// 3. 发生请求client.indices().create(request, RequestOptions.DEFAULT);}

运行成功后我们回到Dev Tools查询

GET /usr

在这里插入图片描述

删除和查看索引库

    @Testvoid deleteHotelIndex() throws IOException {DeleteIndexRequest request = new DeleteIndexRequest("user");client.indices().delete(request, RequestOptions.DEFAULT);}@Testvoid existsHotelIndex() throws IOException {GetIndexRequest request = new GetIndexRequest("user");boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);System.out.println(exists ? "索引库已经存在" : "索引库不存在");}

RestClient操作文档

准备工作

这里我们配合mysql来完成文档的操作,要使用mybatis-plus,所以给该测试类加上@SpringBootTest,并注入相应的mapper或者service。
user的sql语句

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (`id` bigint(25) NOT NULL AUTO_INCREMENT,`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;INSERT INTO `tb_user` VALUES (1, 'zhangsan');
INSERT INTO `tb_user` VALUES (2, 'lisi');
INSERT INTO `tb_user` VALUES (3, 'wangwu');
INSERT INTO `tb_user` VALUES (4, 'zhaoliu');
INSERT INTO `tb_user` VALUES (5, 'xiaomei');
INSERT INTO `tb_user` VALUES (6, 'xiaobai');
INSERT INTO `tb_user` VALUES (7, 'at');
INSERT INTO `tb_user` VALUES (8, 'sh');
INSERT INTO `tb_user` VALUES (9, 'wsgp');
INSERT INTO `tb_user` VALUES (10, 'iop');
INSERT INTO `tb_user` VALUES (11, 'askdhgk');

user实体类

package cn.itcast.hotel.pojo;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;@Data
@TableName("tb_user")
public class User {@TableId(type = IdType.INPUT)private Long id;private String Name;
}

UserMapper类

package cn.itcast.hotel.mapper;import cn.itcast.hotel.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;public interface UserMapper extends BaseMapper<User> {
}

单个文档插入

    @Testvoid addDoc() throws IOException {User user = userMapper.selectById(1);System.out.println(user);IndexRequest request = new IndexRequest("user").id(user.getId().toString());request.source(JSON.toJSONString(user), XContentType.JSON);client.index(request, RequestOptions.DEFAULT);}

查看是否插入成功:
在这里插入图片描述

查询文档

    @Testvoid getDoc() throws IOException {GetRequest request = new GetRequest("user", "1");GetResponse response = client.get(request, RequestOptions.DEFAULT);String json = response.getSourceAsString();User user = JSON.parseObject(json, User.class);System.out.println(user);}

在这里插入图片描述

更新和删除文档

这里有全量更新和局部更新,全量更新就和插入文档一样,所以这里只介绍局部更新。

    /*** 局部更新*/@Testvoid updateDoc() throws IOException {UpdateRequest request = new UpdateRequest("user", "1");request.doc("name", "zs");client.update(request, RequestOptions.DEFAULT);}/*** 删除指定文档* @throws IOException*/@Testvoid deleteDoc() throws IOException {DeleteRequest request = new DeleteRequest("user", "1");client.delete(request, RequestOptions.DEFAULT);}

在这里插入图片描述
在这里插入图片描述

批量插入文档

    /*** 批量插入* @throws IOException*/@Testvoid addDocBulk() throws IOException {List<User> users = userMapper.selectList(null);BulkRequest request = new BulkRequest();for (User user : users) {request.add(new IndexRequest("test").id(user.getId().toString()).source(JSON.toJSONString(user), XContentType.JSON));}client.bulk(request, RequestOptions.DEFAULT);}

在这里插入图片描述

http://www.lryc.cn/news/377133.html

相关文章:

  • 【设计模式深度剖析】【11】【行为型】【解释器模式】| 以算术表达式求值为例加深理解
  • MySQL8,Navicat能登陆成功,密码却忘记了
  • 游戏中的寻路算法研究
  • 【AWS SMB】关于AWS 中小型企业 (SMB) 能力介绍及注意事项
  • 中年之恋:重返青春的旅程
  • 人工智能中的监督学习和无监督学习
  • 深度学习500问——Chapter12:网络搭建及训练(1)
  • HuggingFace CLI 命令全面指南
  • FreeRTOS源码分析
  • python实战:将视频内容上传到社交媒体平台
  • 【深度学习】sdwebui A1111 加速方案对比,xformers vs Flash Attention 2
  • 5分钟了解单元测试
  • VSCode之C/C++插件之宏定义导致颜色变暗
  • 自然语言处理概述
  • 用Rust和Pingora轻松构建超越Nginx的高效负载均衡器
  • 华为云与AWS负载均衡服务深度对比:性能、成本与可用性
  • Vue65-组件之间的传值
  • Java零基础之多线程篇:线程生命周期
  • 技术差异,应用场景;虚拟机可以当作云服务器吗
  • Qt Quick 教程(一)
  • react钩子函数用法(useCallback、useMemo)
  • linux配置Vnc Server给Windows连接
  • Android中的KeyEvent详解
  • 移植案例与原理 - HDF驱动框架-驱动配置(2)
  • 年终奖发放没几天,提离职领导指责我不厚道,我该怎么办?
  • 多处理系统结构
  • 创建进程的常用方式
  • 李宏毅2023机器学习作业HW06解析和代码分享
  • 专业技能篇--算法
  • Vue中CSS动态样式绑定