为了与索引库操作分离,我们再次加一个测试类,做两件事情:
RestHighLevelClient
IHotelService
去查询,所以注入这个接口package com.dcxuexi.hotel;
import com.dcxuexi.hotel.service.IHotelService;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
/***
* @Title HotelDocumentTest
* @Description TOTD
* @Auter DongChuang
* @Date 2023/4/3 19:44
* @Version 1.0.0
*/
@SpringBootTest
public class HotelDocumentTest {
@Autowired
private IHotelService HotelService;
private RestHighLevelClient client;
@BeforeEach
void setup(){
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("https:192.168.1.111:9200")
));
}
@AfterEach
void tearDown() throws IOException {
this.client.close();
}
}
我们要将数据库的酒店数据查询出来,写入elasticsearch
中。
数据库查询后的结果是一个Hotel
类型的对象。结构如下:
package com.dcxuexi.hotel.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.dcxuexi.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();
}
}
新增文档的DSL
语句如下:
POST /{索引库名}/_doc/1
{
"name": "Jack",
"age": 21
}
对应的java
代码:
@Test
void testIndexDocument() throws IOException {
//1. 创建request对象 索引库名:indexName 文档id:1
IndexRequest indexRequest = new IndexRequest("indexName").id("1");
//2. 准备json文档 {"name": "Jack","age": 21}
indexRequest.source("{\"name\": \"Jack\",\"age\": 21}", XContentType.JSON);
//3. 发送请求
client.index(indexRequest, 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
,因此难点是结果的解析。完整代码如下:
可以看到,结果是一个JSON
,其中文档放在一个_source
属性中,因此解析就是拿到_source
,反序列化为Java
对象即可。
与之前类似,也是三步走:
Request
对象。这次是查询,所以是GetRequest
client.get()
方法JSON
做反序列化在hotel-demo
的HotelDocumentTest
测试类中,编写单元测试:
@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();
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println("hotelDoc = " + hotelDoc);
}
删除的DSL
为是这样的:
DELETE /hotel/_doc/{id}
与查询相比,仅仅是请求方式从DELETE
变成GET
,可以想象Java
代码应该依然是三步走:
Request
对象,因为是删除,这次是DeleteRequest
对象。要指定索引库名和id
client.delete()
方法在hotel-demo
的HotelDocumentTest
测试类中,编写单元测试:
@Test
void testDeleteDocument() throws IOException {
// 1.准备Request
DeleteRequest request = new DeleteRequest("indexName", "1");
// 2.发送请求
client.delete(request, RequestOptions.DEFAULT);
}
修改我们介绍两种方式:
id
删除,再新增在RestClient
的API
中,全量修改与新增的API
完全一致,判断依据是ID
:
ID
已经存在,则修改ID
不存在,则新增这里不再赘述,我们主要关注增量修改。
代码示例如图:
与之前类似,也是三步走:
Request
对象。这次是修改,所以是UpdateRequest
JSON
文档,里面包含要修改的字段client.update()
方法在hotel-demo
的HotelDocumentTest
测试类中,编写单元测试:
@Test
void testUpdateDocument() throws IOException {
// 1.准备Request
UpdateRequest request = new UpdateRequest("hotel", "1");
// 2.准备请求参数
request.doc(
"age", "18",
"name", "Rose"
);
// 3.发送请求
client.update(request, RequestOptions.DEFAULT);
}
案例需求:利用BulkRequest
批量将数据库数据导入到索引库中。
步骤如下:
利用mybatis-plus
查询酒店数据
将查询到的酒店数据(Hotel
)转换为文档类型数据(HotelDoc
)
利用JavaRestClient
中的BulkRequest
批处理,实现批量新增文档
批量处理BulkRequest
,其本质就是将多个普通的CRUD
请求组合在一起发送。
其中提供了一个add
方法,用来添加其他请求:
可以看到,能添加的请求包括:
IndexRequest
,也就是新增UpdateRequest
,也就是修改DeleteRequest
,也就是删除因此Bulk
中添加了多个IndexRequest
,就是批量新增功能了。示例:
其实还是三步走:
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);
}
文档操作的基本步骤:
RestHighLevelClient
XxxRequest
。XXX
是Index
、Get
、Update
、Delete
、Bulk
Index
、Update
、Bulk
时需要)RestHighLevelClient#.xxx()
方法,xxx
是index
、get
、update
、delete
、bulk
Get
时需要)