HM-SpringCloud微服务系列5.5【RestClient操作文档】
为了与索引库操作分离,我们再次参加一个测试类,做两件事情:
- 初始化RestHighLevelClient
- 我们的酒店数据在数据库,需要利用IHotelService去查询,所以注入这个接口
package cn.itcast.hotel;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.service.IHotelService;
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.List;
@SpringBootTest
public class HotelDocumentTest {
@Autowired
private IHotelService hotelService;
private RestHighLevelClient client;
@BeforeEach
void setUp() {
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.150.101:9200")
));
}
@AfterEach
void tearDown() throws IOException {
this.client.close();
}
}
1 新增文档
1.1 语法说明
新增文档的DSL语句如下:
POST /{索引库名}/_doc/1
{
"name": "Jack",
"age": 21
}
可以看到与创建索引库类似,同样是三步走:
- 1)创建Request对象
- 2)准备请求参数,也就是DSL中的JSON文档
- 3)发送请求
变化的地方在于,这里直接使用client.xxx()的API,不再需要client.indices()了。
1.2 索引库实体类
数据库查询后的结果是一个Hotel类型的对象。结构如下:
package com.yppah.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_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;
}
与我们的索引库结构存在差异:longitude和latitude需要合并为location。因此,我们需要定义一个新的类型,与索引库结构吻合:
package com.yppah.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();
}
}
1.3 将数据库的酒店数据查询出来,写入elasticsearch中
@Test
void testAddDocument() throws IOException {
// 1.查询数据库hotel数据
Hotel hotel = hotelService.getById(61083L);
// 2.转换为HotelDoc
HotelDoc hotelDoc = new HotelDoc(hotel);
// 3.转JSON
String json = JSON.toJSONString(hotelDoc);
// 1.准备Request
IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
// 2.准备请求参数DSL,其实就是文档的JSON字符串
request.source(json, XContentType.JSON);
// 3.发送请求
client.index(request, RequestOptions.DEFAULT);
}
1.4 测试
2 查询文档
2.1 语法
- 查询的DSL语句:
GET /hotel/_doc/{id}
- 因此代码大概分两步:
- 准备Request对象
- 发送请求
- 不过查询的目的是得到结果,解析为HotelDoc,因此难点是结果的解析。
- 结果是一个JSON,其中文档放在一个
_source
属性中,因此解析就是拿到_source
,反序列化为Java对象即可。 - 与之前新增文档类似,也是三步走:
- 1)准备Request对象。这次是查询,所以是GetRequest
- 2)发送请求,得到结果。因为是查询,这里调用client.get()方法
- 3)解析结果,就是对JSON做反序列化
2.2 代码
在hotel-demo的HotelDocumentTest测试类中,编写单元测试:
@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);
}
2.3 测试
实测:貌似在获取前,自动先删除了,然后就获取不到了,不知道为啥
解决:
3 修改文档
3.1 两种修改方式
- 全量&增量
- 全量修改:本质是先根据id删除,再新增
- 增量修改:修改文档中的指定字段值
- 在RestClient的API中,全量修改与新增的API完全一致,判断依据是ID:
- 如果新增时,ID已经存在,则修改
- 如果新增时,ID不存在,则新增
- 这里不再赘述,我们主要关注增量修改。
- 与之前类似,也是三步走:
- 1)准备Request对象。这次是修改,所以是UpdateRequest
- 2)准备参数。也就是JSON文档,里面包含要修改的字段
- 3)更新文档。这里调用client.update()方法
3.2 代码
在hotel-demo的HotelDocumentTest测试类中,编写单元测试:
@Test
void testUpdateDocument() throws IOException {
// 1.准备Request
UpdateRequest request = new UpdateRequest("hotel", "61083");
// 2.准备请求参数
request.doc(
"price", "870",
"score", "47"
);
// 3.发送请求
client.update(request, RequestOptions.DEFAULT);
}
3.3 测试
更新前:
更新后:
4 删除文档
4.1 语法
DELETE /hotel/_doc/{id}
与查询相比,仅仅是请求方式从DELETE变成GET,可以想象Java代码应该依然是三步走:
- 1)准备Request对象,因为是删除,这次是DeleteRequest对象。要指定索引库名和id
- 2)准备参数,无参
- 3)发送请求。因为是删除,所以是client.delete()方法
4.2 代码
在hotel-demo的HotelDocumentTest测试类中,编写单元测试:
@Test
void testDeleteDocument() throws IOException {
// 1.准备Request
DeleteRequest request = new DeleteRequest("hotel", "61083");
// 2.发送请求
client.delete(request, RequestOptions.DEFAULT);
}
4.3 测试
删除前:
删除后:
5 批量导入文档
利用BulkRequest批量将数据库数据导入到索引库中。
5.1 语法
-
批量处理BulkRequest,其本质就是将多个普通的CRUD请求组合在一起发送。
-
其中提供了一个add方法,用来添加其他请求:
-
可以看到,能添加的请求包括:
- IndexRequest,也就是新增
- UpdateRequest,也就是修改
- DeleteRequest,也就是删除
-
因此Bulk中添加了多个IndexRequest,就是批量新增功能了。示例:
-
其实还是三步走:
- 1)创建Request对象。这里是BulkRequest
- 2)准备参数。批处理的参数,就是其它Request对象,这里就是多个IndexRequest
- 3)发起请求。这里是批处理,调用的方法为client.bulk()方法
5.2 代码
在hotel-demo的HotelDocumentTest测试类中,编写单元测试:
@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);
}
5.3 测试
{
"took" : 446,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 201,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "36934",
"_score" : 1.0,
"_source" : {
"address" : "静安交通路40号",
"brand" : "7天酒店",
"business" : "四川北路商业区",
"city" : "上海",
"id" : 36934,
"location" : "31.251433, 121.47522",
"name" : "7天连锁酒店(上海宝山路地铁站店)",
"pic" : "https://m.tuniucdn.com/fb2/t1/G1/M00/3E/40/Cii9EVkyLrKIXo1vAAHgrxo_pUcAALcKQLD688AAeDH564_w200_h200_c1_t0.jpg",
"price" : 336,
"score" : 37,
"starName" : "二钻"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "38609",
"_score" : 1.0,
"_source" : {
"address" : "广灵二路126号",
"brand" : "速8",
"business" : "四川北路商业区",
"city" : "上海",
"id" : 38609,
"location" : "31.282444, 121.479385",
"name" : "速8酒店(上海赤峰路店)",
"pic" : "https://m.tuniucdn.com/fb2/t1/G2/M00/DF/96/Cii-TFkx0ImIQZeiAAITil0LM7cAALCYwKXHQ4AAhOi377_w200_h200_c1_t0.jpg",
"price" : 249,
"score" : 35,
"starName" : "二钻"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "38665",
"_score" : 1.0,
"_source" : {
"address" : "兰田路38号",
"brand" : "速8",
"business" : "长风公园地区",
"city" : "上海",
"id" : 38665,
"location" : "31.244288, 121.422419",
"name" : "速8酒店上海中山北路兰田路店",
"pic" : "https://m.tuniucdn.com/fb2/t1/G2/M00/EF/86/Cii-Tlk2mV2IMZ-_AAEucgG3dx4AALaawEjiycAAS6K083_w200_h200_c1_t0.jpg",
"price" : 226,
"score" : 35,
"starName" : "二钻"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "38812",
"_score" : 1.0,
"_source" : {
"address" : "徐汇龙华西路315弄58号",
"brand" : "7天酒店",
"business" : "八万人体育场地区",
"city" : "上海",
"id" : 38812,
"location" : "31.174377, 121.442875",
"name" : "7天连锁酒店(上海漕溪路地铁站店)",
"pic" : "https://m.tuniucdn.com/fb2/t1/G2/M00/E0/0E/Cii-TlkyIr2IEWNoAAHQYv7i5CkAALD-QP2iJwAAdB6245_w200_h200_c1_t0.jpg",
"price" : 298,
"score" : 37,
"starName" : "二钻"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "39106",
"_score" : 1.0,
"_source" : {
"address" : "闵行莘庄镇七莘路299号",
"brand" : "7天酒店",
"business" : "莘庄工业区",
"city" : "上海",
"id" : 39106,
"location" : "31.113812, 121.375869",
"name" : "7天连锁酒店(上海莘庄地铁站店)",
"pic" : "https://m.tuniucdn.com/fb2/t1/G2/M00/D8/11/Cii-T1ku2zGIGR7uAAF1NYY9clwAAKxZAHO8HgAAXVN368_w200_h200_c1_t0.jpg",
"price" : 348,
"score" : 41,
"starName" : "二钻"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "39141",
"_score" : 1.0,
"_source" : {
"address" : "杨浦国权路315号",
"brand" : "7天酒店",
"business" : "江湾、五角场商业区",
"city" : "上海",
"id" : 39141,
"location" : "31.290057, 121.508804",
"name" : "7天连锁酒店(上海五角场复旦同济大学店)",
"pic" : "https://m.tuniucdn.com/fb2/t1/G2/M00/C7/E3/Cii-T1knFXCIJzNYAAFB8-uFNAEAAKYkQPcw1IAAUIL012_w200_h200_c1_t0.jpg",
"price" : 349,
"score" : 38,
"starName" : "二钻"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "45845",
"_score" : 1.0,
"_source" : {
"address" : "虹桥路100号",
"brand" : "万怡",
"business" : "徐家汇地区",
"city" : "上海",
"id" : 45845,
"location" : "31.192714, 121.434717",
"name" : "上海西藏大厦万怡酒店",
"pic" : "https://m.tuniucdn.com/fb3/s1/2n9c/48GNb9GZpJDCejVAcQHYWwYyU8T_w200_h200_c1_t0.jpg",
"price" : 589,
"score" : 45,
"starName" : "四钻"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "45870",
"_score" : 1.0,
"_source" : {
"address" : "新元南路555号",
"brand" : "豪生",
"business" : "滴水湖临港地区",
"city" : "上海",
"id" : 45870,
"location" : "30.871729, 121.81959",
"name" : "上海临港豪生大酒店",
"pic" : "https://m.tuniucdn.com/fb3/s1/2n9c/2F5HoQvBgypoDUE46752ppnQaTqs_w200_h200_c1_t0.jpg",
"price" : 896,
"score" : 45,
"starName" : "四星级"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "46829",
"_score" : 1.0,
"_source" : {
"address" : "恒丰路338号",
"brand" : "万怡",
"business" : "上海火车站地区",
"city" : "上海",
"id" : 46829,
"location" : "31.242977, 121.455864",
"name" : "上海浦西万怡酒店",
"pic" : "https://m.tuniucdn.com/fb3/s1/2n9c/x87VCoyaR8cTuYFZmKHe8VC6Wk1_w200_h200_c1_t0.jpg",
"price" : 726,
"score" : 46,
"starName" : "四钻"
}
},
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "47066",
"_score" : 1.0,
"_source" : {
"address" : "施新路958号",
"brand" : "华美达",
"business" : "浦东机场核心区",
"city" : "上海",
"id" : 47066,
"location" : "31.147989, 121.759199",
"name" : "上海浦东东站华美达酒店",
"pic" : "https://m.tuniucdn.com/fb3/s1/2n9c/2pNujAVaQbXACzkHp8bQMm6zqwhp_w200_h200_c1_t0.jpg",
"price" : 408,
"score" : 46,
"starName" : "四钻"
}
}
]
}
}
6 小结
- 文档操作的基本步骤:
- 初始化RestHighLevelClient
- 创建XxxRequest。XXX是Index、Get、Update、Delete、Bulk
- 准备参数(Index、Update、Bulk时需要)
- 发送请求。调用RestHighLevelClient#.xxx()方法,xxx是index、get、update、delete、bulk
- 解析结果(Get时需要)