目录
一、新增文档
1、编写测试代码
java
@SpringBootTest
public class HotelDocumentTest {
private RestHighLevelClient client;
@Autowired
private IHotelService iHotelService;
@Test
void testInit(){
System.out.println(client);
}
@BeforeEach
void setUp(){
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.248.152:9200")
));
}
@AfterEach
void tearDown() throws IOException {
this.client.close();
}
@Test
void 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、编写测试代码
java
@Test
void testGetDocument() throws IOException {
// 准备request对象
GetRequest request = new GetRequest("hotel","61083");
// 接收response
GetResponse response = client.get(request,RequestOptions.DEFAULT);
// 解析
String json = response.getSourceAsString();
HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
System.out.println(hotelDoc);
}
三、删除文档
1、编写测试代码
java
@Test
void testDeleteDocument() throws IOException {
// 准备request对象
DeleteRequest request = new DeleteRequest("hotel","61083");
// 发送请求
client.delete(request,RequestOptions.DEFAULT);
}
四、修改文档
1、编写测试代码
java
@Test
void testUpdateDocument() throws IOException {
// 准备request对象
UpdateRequest request = new UpdateRequest("hotel","61083");
// 准备请求参数
request.doc(
"price","952",
"starName","四钻 "
);
// 发送请求
client.update(request,RequestOptions.DEFAULT);
}
五、批量导入文档
java
void testBulkRequest() throws IOException{
// 批量查询酒店数据
List<Hotel> hotelList = iHotelService.list();
// 创建Request
BulkRequest request = new BulkRequest();
// 准备参数
for (Hotel hotel : hotelList){
// 转换为文档类型HotelDoc
HotelDoc 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);
}