RestClient操作文档

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: 基础配置新增文档查询文档删除文档修改文档批量导入文档总结

基础配置

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时需要)
相关实践学习
利用Elasticsearch实现地理位置查询
本实验将分别介绍如何使用Elasticsearch7.10版本进行全文检索、多语言检索和地理位置查询三个Elasticsearch基础检索子场景的实现。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
相关文章
|
2月前
Elasticsearch之RestClient查询文档
Elasticsearch之RestClient查询文档
153 1
|
API 对象存储 网络架构
OSS restful API 调用 put,上传文件,python发http request示例
发送put 请求,向bucket中写入文件,代码中*** 的部分改成实际内容。rest请求主要问题在拼header时authorization可能会有问题,注意生成signature时的入参。#tested env: python version v3.9.6 #author: Fred #2022-1-11 import hmac import hashlib import base64 im
1102 0
|
JSON API 网络架构
基于Moya、RxSwift和ObjectMapper优雅实现REST API请求
在Android开发中有非常强大的 Retrofit 请求,结合RxJava可以非常方便实现 RESTful API 网络请求。在 iOS开发中也有非常强大的网络请求库 Moya ,Moya是一个基于 Alamofire 开发的,轻量级的Swift网络层。
2041 0
|
2月前
|
Linux API 网络架构
Rest API请求管理最佳实践:RestClient-cpp库的应用案例
Rest API请求管理最佳实践:RestClient-cpp库的应用案例
|
2月前
|
JSON 搜索推荐 API
【2024更新】如何使用google index api来自动提交url
本文提供了一个详细的指南,说明如何创建并使用使用google index api,google自动提交url来优化seo。
83 0
|
12月前
|
JSON Java 测试技术
【Elasticsearch】RestClient操作文档
【Elasticsearch】RestClient操作文档
99 0
FastAPI(36)- FastAPI 的元数据配置和文档 URL
FastAPI(36)- FastAPI 的元数据配置和文档 URL
391 0
FastAPI(36)- FastAPI 的元数据配置和文档 URL
|
JSON 物联网 开发工具
CZGL.AliloTClient 文档:说明
CZGL.AliloTClient 文档:说明
94 0
CZGL.AliloTClient 文档:说明
|
API 对象存储 网络架构
OSS restful API 调用 Delete,删除文件,python发http request示例
发送delete 请求删除bucket中的文件,代码中*** 的部分改成实际内容。rest请求主要问题在拼header时authorization可能会有问题。#tested env: python version v3.9.6 #author: Fred #2022-1-11 import hmac import hashlib import base64 import datetime im
406 0
|
API 对象存储 网络架构
OSS restful API 调用 get,遍历目录中的文件,python发http request示例
发送get 请求,遍历目录下的所有文件,代码中*** 的部分改成实际内容,这个API说明文档在bucket操作里面。rest请求主要问题在拼header时authorization可能会有问题,注意计算签名时的入参。#tested env: python version v3.9.6 #author: Fred #2022-1-11 import hmac import hashlib impo
615 0