目录
一、新增文档
1、编写测试代码
二、查询文档
1、编写测试代码
三、删除文档
1、编写测试代码
四、修改文档
1、编写测试代码
五、批量导入文档
批量查询
一、新增文档
1、编写测试代码
@SpringBootTest
public class HotelDocumentTest {private RestHighLevelClient client;@Autowiredprivate IHotelService iHotelService;@Testvoid testInit(){System.out.println(client);}@BeforeEachvoid setUp(){this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.248.152:9200")));}@AfterEachvoid tearDown() throws IOException {this.client.close();}@Testvoid testAddDocument() throws IOException {Hotel hotel = iHotelService.getById(61083L);HotelDoc hotelDoc = new HotelDoc(hotel);
// 准备request对象IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
// 准备Json文档request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
// 发送请求client.index(request, RequestOptions.DEFAULT);}}
二、查询文档
1、编写测试代码
@Testvoid testGetDocument() throws IOException {
// 准备request对象GetRequest request = new GetRequest("hotel","61083");
// 接收responseGetResponse response = client.get(request,RequestOptions.DEFAULT);
// 解析String json = response.getSourceAsString();HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);System.out.println(hotelDoc);}
三、删除文档
1、编写测试代码
@Testvoid testDeleteDocument() throws IOException {
// 准备request对象DeleteRequest request = new DeleteRequest("hotel","61083");
// 发送请求client.delete(request,RequestOptions.DEFAULT);}
四、修改文档
1、编写测试代码
@Testvoid testUpdateDocument() throws IOException {
// 准备request对象UpdateRequest request = new UpdateRequest("hotel","61083");
// 准备请求参数request.doc("price","952","starName","四钻 ");
// 发送请求client.update(request,RequestOptions.DEFAULT);}
五、批量导入文档
void testBulkRequest() throws IOException{
// 批量查询酒店数据List<Hotel> hotelList = iHotelService.list();
// 创建RequestBulkRequest request = new BulkRequest();
// 准备参数for (Hotel hotel : hotelList){
// 转换为文档类型HotelDocHotelDoc hotelDoc = new HotelDoc(hotel);
// 创建新增文档的Request对象request.add(new IndexRequest("hotel").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc),XContentType.JSON));}
// 发送请求client.bulk(request,RequestOptions.DEFAULT);}