因为数据库里面的字段跟我们的索引库的字段其实是有差异的
所以我们必须要整一个跟索引库字段的实体类
是为了实现数据库的数据到索引库的数据的类型转换
package cn.itcast.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();
}
}
@Test
void TestAddDoument() throws IOException {
//根据ID查询数据
Hotel hotel = hotelService.getById(60363L);
//转换为文档类型
HotelDoc hotelDoc = new HotelDoc(hotel);
//准备requet文档对象
IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
//准备json文档 将文档内容序列化json数据
request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
//发送请求
client.index(request,RequestOptions.DEFAULT);
}
根据ID 查询酒店数据:
/**
* 根据ID 查询文档
*/
@Test
void TestSelectDoucment() throws IOException {
//获取请求对象 索引库名称和文档的ID
GetRequest getRequest = new GetRequest("hotel","60363");
//发送请求 得到响应
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
//解析结果
String json = response.getSourceAsString();
System.out.println(json);
//反序列化
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println(hotelDoc);
}
更新文档:
全量更新
局部更新:
/**
* 更新
*/
@Test
void testUpdateDocument() throws IOException {
//准备request
UpdateRequest request = new UpdateRequest("hotel","60363");
//准备请求参数
request.doc(
//key value
"price","8989789",
"address","北戴河之光"
);
//发送请求
client.update(request,RequestOptions.DEFAULT);
}
删除文档:
/**
* 删除
*/
@Test
void testDelet() throws IOException {
//准备request
DeleteRequest request = new DeleteRequest("hotel","60363");
//发送请求
client.delete(request,RequestOptions.DEFAULT);
}
批量导入文档:
/**
* 批量添加
*/
@Test
void testBulkRequest() throws IOException {
//批量查询数据库里面的酒店数据
List<Hotel> list = hotelService.list();
//创建请求对象
BulkRequest bulkRequest = new BulkRequest();
//准备参数 添加多个新增的request
//转换为文档类型
for (Hotel hotel : list) {
HotelDoc hotelDoc = new HotelDoc(hotel);
bulkRequest.add(new IndexRequest("hotel").
id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc),XContentType.JSON));
}
bulkRequest.add(new IndexRequest("hotel").id("61038").source("json",XContentType.JSON));
bulkRequest.add(new IndexRequest("hotel").id("61038").source("json",XContentType.JSON));