RestClient操作文档

本文涉及的产品
Elasticsearch Serverless通用抵扣包,测试体验金 200元
简介: 基础配置新增文档查询文档删除文档修改文档批量导入文档总结

基础配置

1.数据库实体类

@Data
@TableName("tb_hotel")
public class Hotel {
    @TableId(type = IdType.INPUT)
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String longitude;
    private String latitude;
    private String pic;
}


2.因为数据库实体类和索引库实体类存在区别,所以进行一定的改动

package com.elasticsearch.hotel.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class HotelDoc {
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;
    private String pic;
    public HotelDoc(Hotel hotel) {
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
        this.pic = hotel.getPic();
    }
}


3.初始化RestHighLevelClient,同时注册IHotelService接口

package com.elasticsearch.hotel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.elasticsearch.hotel.constants.HotelConstants;
import com.elasticsearch.hotel.pojo.Hotel;
import com.elasticsearch.hotel.pojo.HotelDoc;
import com.elasticsearch.hotel.service.IHotelService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.Map;
@SpringBootTest
public class HotelDocumentTest {
    @Autowired
    private IHotelService iHotelService ;
    private RestHighLevelClient client;
   @BeforeEach
   void setUp(){
       this.client = new RestHighLevelClient(RestClient.builder(
               HttpHost.create("http://localhost:9200")
       ));
   }
   @AfterEach
    void tearDown() throws IOException {
       this.client.close();
   }
}


新增文档

@Test
void testAddDocument() throws IOException {
    // 1.根据id查询酒店数据
    Hotel hotel = hotelService.getById(61083L);
    // 2.转换为文档类型
    HotelDoc hotelDoc = new HotelDoc(hotel);
    // 3.将HotelDoc转json
    String json = JSON.toJSONString(hotelDoc);
    // 1.准备Request对象
    IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
    // 2.准备Json文档
    request.source(json, XContentType.JSON);
    // 3.发送请求
    client.index(request, RequestOptions.DEFAULT);
}


查询文档


@Test
void testGetDocumentById() throws IOException {
    // 1.准备Request
    GetRequest request = new GetRequest("hotel", "61082");
    // 2.发送请求,得到响应
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    // 3.解析响应结果
    String json = response.getSourceAsString();
    HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
    System.out.println(hotelDoc);
}


删除文档


@Test
void testDeleteDocument() throws IOException {
    // 1.准备Request
    DeleteRequest request = new DeleteRequest("hotel", "61083");
    // 2.发送请求
    client.delete(request, RequestOptions.DEFAULT);
}


修改文档

@Test
void testUpdateDocument() throws IOException {
    // 1.准备Request
    UpdateRequest request = new UpdateRequest("hotel", "61083");
    // 2.准备请求参数
    request.doc(
        "price", "952",
        "starName", "四钻"
    );
    // 3.发送请求
    client.update(request, RequestOptions.DEFAULT);
}


批量导入文档

@Test
void testBulkRequest() throws IOException {
    // 批量查询酒店数据
    List<Hotel> hotels = hotelService.list();
    // 1.创建Request
    BulkRequest request = new BulkRequest();
    // 2.准备参数,添加多个新增的Request
    for (Hotel hotel : hotels) {
        // 2.1.转换为文档类型HotelDoc
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 2.2.创建新增文档的Request对象
        request.add(new IndexRequest("hotel")
                    .id(hotelDoc.getId().toString())
                    .source(JSON.toJSONString(hotelDoc), XContentType.JSON));
    }
    // 3.发送请求
    client.bulk(request, RequestOptions.DEFAULT);
}


总结

初始化RestHighLevelClient
创建XxxRequest。XXX是Index、Get、Update、Delete、Bulk
准备参数(Index、Update、Bulk时需要)
发送请求。调用RestHighLevelClient#.xxx()方法,xxx是index、get、update、delete、bulk
解析结果(Get时需要)
相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
相关文章
|
存储 分布式计算 资源调度
2022年最强大数据面试宝典(全文50000字,建议收藏)(一)
复习大数据面试题,看这一套就够了!
2814 0
|
6月前
|
传感器 人工智能 物联网
健康监测设备的技术革命:AI+物联网如何让你随时掌握健康数据?
健康监测设备的技术革命:AI+物联网如何让你随时掌握健康数据?
851 19
|
存储 Java 关系型数据库
Java分布式事务及seata框架的使用
什么是事务? 事务从本质上讲就是:逻辑上的一组操作,组成这组操作的各个逻辑单元在不同的服务甚至服务器上,保证它们要成功就都成功,要失败就都失败。 事务的四大特性 提到事务就不得不提事务的四大特性(基本特征) ACID: 原子性(atomicity):“原子”的本意是“不可再分”,事务的原子性表现为一个事务中涉及到的多个操作在逻辑上缺一不可。事务的原子性要求事务中的所有操作要么都执行,要么都不执行。 一致性(consistency):“一致”指的是数据的一致,具体是指:所有数据都处于满足业务规则的一致性状态。一致性原则要求:一个事务中不管涉及到多少个操作,都必须保证事务执行之前数据是正确的
|
机器学习/深度学习 运维 监控
一文速览深度伪造检测(Detection of Deepfakes):未来技术的守门人
一文速览深度伪造检测(Detection of Deepfakes):未来技术的守门人
2795 0
|
运维 监控 Devops
DevOps 入门:基础知识与核心理念
【8月更文第30天】随着软件开发的复杂性和速度不断增加,传统的开发模式已经无法满足市场需求。DevOps 应运而生,它不仅是一种实践方法,也是一种文化和理念,旨在通过自动化和持续改进来提高软件交付的速度和质量。
608 1
|
安全 Java API
深入了解java.util.Date类:历史、功能和使用注意事项
本文详细介绍了Java中的`java.util.Date`类,包括其历史、基本功能和使用时的注意事项。`Date`类最初用于简单表示日期和时间,但随着发展暴露出了不可变性、线程安全性和时区处理等问题。文章展示了如何创建和操作日期,以及如何使用`SimpleDateFormat`进行日期格式化和解析。虽然Java 8引入了更好的`java.time`包,但理解`Date`类仍然很重要,特别是处理旧代码或兼容性问题时。注意`Date`类的废弃方法、非线程安全性质以及月份从0开始等细节。
453 1
|
11月前
|
光互联
常见网络电缆类型详解
【10月更文挑战第14天】
312 0
|
设计模式 前端开发 Java
【Spring MVC】快速学习使用Spring MVC的注解及三层架构
【Spring MVC】快速学习使用Spring MVC的注解及三层架构
357 1
|
消息中间件 缓存 NoSQL
利用Redis实现高效缓存管理与加速
本文将探讨如何利用Redis作为缓存管理工具,通过深入分析Redis的特性、使用场景和优势,帮助开发人员更好地理解和应用Redis来提升系统性能和响应速度。
[Qt5] 实现CAD中的十字标辅助线效果
[Qt5] 实现CAD中的十字标辅助线效果
409 0