去数据库查询酒店数据,导入到 hotel 索引库,实现酒店数据的 CRUD。基本步骤如下:
- 初始化 JavaRestClient
- 利用 JavaRestClient 新增酒店数据
- 利用 JavaRestClient 根据id查询酒店数据
- 利用 JavaRestClient 删除酒店数据
- 利用 JavaRestClient 修改酒店数据
初始化 JavaRestClient
为了与索引库操作分离,我们再次参加一个测试类,做两件事情:
- 初始化 RestHighLevelClient,同上
我们的酒店数据在数据库,需要利用 IHotelService 去查询,所以注入这个接口
@SpringBootTestpublic class HotelDocumentTest {@Autowiredprivate IHotelService hotelService;private RestHighLevelClient client;@BeforeEachvoid setUp() {this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://halo:9200")));}@AfterEachvoid tearDown() throws IOException {this.client.close();}}
新增文档
我们要将数据库的酒店数据查询出来,写入 ElasticSearch 中。
索引库实体类
数据库查询后的结果是一个 Hotel 类型的对象。结构如下:
@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 cn.itcast.hotel.pojo;import lombok.Data;import lombok.NoArgsConstructor;@Data@NoArgsConstructorpublic 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();}}
语法说明
新增文档的 DSL 语句如下:
POST /{索引库名}/_doc/1{"name": "Jack","age": 21}
对应的 Java 代码如下:
@Test
void testIndexDocument() throws IOException {
// 1.创建request对象
IndexRequest request = new IndexRequest("indexName").id("1");
// 2.准备JSON文档
request.source("{\"name\": \"Jack\", \"age\": 21}", XContentType.JSON);
// 3.发送请求
client.index(request, RequestOptions.DEFAULT);
}
可以看到与创建索引库类似,同样是三步走:
- 创建 Request 对象
- 准备请求参数,也就是 DSL 中的 JSON 文档
- 发送请求
变化的地方在于,这里直接使用 client.xxx() 的 API,不再需要 client.indices() 了。
完整代码
我们导入酒店数据,基本流程一致,但是需要考虑几点变化:
- 酒店数据来自于数据库,我们需要先查询出来,得到 Hotel 对象
- Hotel 对象需要转为 HotelDoc对象
- HotelDoc 需要序列化为 JSON 格式
因此,代码整体步骤如下:
- 根据 id 查询酒店数据 Hotel
- 将 Hotel 封装为 HotelDoc
- 将 HotelDoc 序列化为 JSON
- 创建 IndexRequest,指定索引库名和 id
- 准备请求参数,也就是 JSON 文档
- 发送请求
在 hotel-demo 的 HotelDocumentTest 测试类中,编写单元测试:
@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);
}
查询文档
语法说明
查询的 DSL 语句如下:
GET /hotel/_doc/{id}
非常简单,因此代码大概分两步:
- 准备 Request 对象
- 发送请求
不过查询的目的是得到结果,解析为 HotelDoc,因此难点是结果的解析。示例代码如下:
@Test
void testGetDocumentById() throws IOException {
// 1.创建request对象
GetRequest request = new GetRequest("indexName", "1");
// 2.发送请求,得到结果
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 3.解析结果
String json = response.getSourceAsString();
System.out.println(json);
}
可以看到,结果是一个 JSON,其中文档放在一个 _source 属性中,因此解析就是拿到 _source,反序列化为 Java 对象即可。
与之前类似,也是三步走:
- 准备 Request 对象。这次是查询,所以是 GetRequest
- 发送请求,得到结果。因为是查询,这里调用
client.get()方法 - 解析结果,就是对 JSON 做反序列化
完整代码
在 hotel-demo 的 HotelDocumentTest 测试类中,编写单元测试:
@Test
void testGetDocumentById() 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);
}
修改文档
语法说明
修改我们讲过两种方式:
- 量修改:本质是先根据id删除,再新增
- 增量修改:修改文档中的指定字段值
在 RestClient 的 API 中,全量修改与新增的 API 完全一致,判断依据是 ID:
- 如果新增时,ID 已经存在,则修改
- 如果新增时,ID 不存在,则新增
这里不再赘述,我们主要关注增量修改。
@Test
void testUpdateDocumentById() throws IOException {
// 1.创建request对象
UpdateRequest request = new UpdateRequest("indexName", "1");
// 2.准备参数,每2个参数为一对 key value
request.doc("age", 18, "name", "Rose");
// 3.更新文档
client.update(request, RequestOptions.DEFAULT);
}
与之前类似,也是三步走:
- 准备 Request 对象。这次是修改,所以是 UpdateRequest
- 准备参数。也就是 JSON 文档,里面包含要修改的字段
- 更新文档。这里调用
client.update()方法
完整代码
在 hotel-demo 的 HotelDocumentTest 测试类中,编写单元测试:
@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);
}
删除文档
删除的 DSL 为是这样的:
DELETE /hotel/_doc/{id}
与查询相比,仅仅是请求方式从 DELETE 变成 GET,可以想象 Java 代码应该依然是三步走:
- 准备 Request 对象,因为是删除,这次是 DeleteRequest 对象。要指定索引库名和 id
- 准备参数,无参
- 发送请求。因为是删除,所以是
client.delete()方法@Test void testDeleteDocument() throws IOException { // 1.准备Request DeleteRequest request = new DeleteRequest("hotel", "61083"); // 2.发送请求 client.delete(request, RequestOptions.DEFAULT); }批量导入文档
案例需求:利用 BulkRequest 批量将数据库数据导入到索引库中。
步骤如下:
- 利用 mybatis-plus 查询酒店数据
- 将查询到的酒店数据(Hotel)转换为文档类型数据(HotelDoc)
- 利用 JavaRestClient 中的 BulkRequest 批处理,实现批量新增文档
语法说明
批量处理 BulkRequest,其本质就是将多个普通的 CRUD 请求组合在一起发送。
其中提供了一个 add 方法,用来添加其他请求:
- IndexRequest,也就是新增
- UpdateRequest,也就是修改
- DeleteRequest,也就是删除
因此 Bulk 中添加了多个 IndexRequest,就是批量新增功能了。示例:
@Test
void testBulk() throws IOException {
// 1.创建Bulk请求
BulkRequest request = new BulkRequest();
// 2.添加要批量提交的请求:这里添加了两个新增文档的请求
request.add(new IndexRequest("hotel")
.id("101").source("json source", XContentType.JSON));
request.add(new IndexRequest("hotel")
.id("102").source("json source2", XContentType.JSON));
// 3.发起bulk请求
client.bulk(request, RequestOptions.DEFAULT);
}
其实还是三步走:
- 创建 Request 对象。这里是 BulkRequest
- 准备参数。批处理的参数,就是其它 Request 对象,这里就是多个 IndexRequest
- 发起请求。这里是批处理,调用的方法为
client.bulk()方法
我们在导入酒店数据时,将上述代码改造成 for 循环处理即可。
完整代码
在 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);
}
测试,批量查询
GET /hotel/_search
Rest Client 文档操作小结
文档操作的基本步骤:
- 初始化 RestHighLevelClient
- 创建 XxxRequest。Xxx 是 Index、Get、Update、Delete、Bulk
- 准备参数(Index、Update、Bulk时需要)
- 发送请求。调用
RestHighLevelClient#.xxx()方法,xxx 是 index、get、update、delete、bulk - 解析结果(Get时需要)
