分布式搜索elaticsearch-数据CRUD操作方法

分布式搜索elaticsearch

数据以文档的形式存储,也需要通过java代码进行基础的CRUD操作。
文档操作的基本步骤

image-20240123201014880

1.新增文档

先从mysql数据库中查询到所需要新增的数据后,将其转换为文档类型,再通过client插入。

@Test
void testDocument() throws IOException {
   
    // 根据id查询酒店数据
    Hotel hotel = hotelService.getById(61083L);
    // 转换为文档类型
    HotelDoc hotelDoc = new HotelDoc(hotel);

    // 1.准备request对象
    IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
    // 2.准备JSON文档
    request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
    // 3.发送请求
    client.index(request, RequestOptions.DEFAULT);
}
2.查询文档
@Test
void testDocumentById() throws IOException {
   
    // 1.准备Request
    GetRequest request = new GetRequest("hotel", "61083");
    // 2.发送请求,得到响应
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    // 3.解析响应结果
    String json = response.getSourceAsString();

    HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
    System.out.println(hotelDoc);
}
3.更新文档

下方代码展示了局部更新的例子,操作只更新提到的参数,其余未提到的参数保持不变。

@Test
void testUpdateDocument() 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值