目錄
一、新增文檔
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);}