


因为数据库里面的字段跟我们的索引库的字段其实是有差异的
所以我们必须要整一个跟索引库字段的实体类
是为了实现数据库的数据到索引库的数据的类型转换
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();}}
@Testvoid 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 查询文档*/@Testvoid TestSelectDoucment() throws IOException {//获取请求对象 索引库名称和文档的IDGetRequest 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);}
更新文档:

全量更新
局部更新:
/*** 更新*/@Testvoid testUpdateDocument() throws IOException {//准备requestUpdateRequest request = new UpdateRequest("hotel","60363");//准备请求参数request.doc(//key value"price","8989789","address","北戴河之光");//发送请求client.update(request,RequestOptions.DEFAULT);}
删除文档:
/*** 删除*/@Testvoid testDelet() throws IOException {//准备requestDeleteRequest request = new DeleteRequest("hotel","60363");//发送请求client.delete(request,RequestOptions.DEFAULT);}

批量导入文档:

/*** 批量添加*/@Testvoid 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));
