个人名片:
本项目基于B站黑马程序员Java《SpringCloud微服务技术栈》,SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
目录
五、RestClient操作文档
案例:利用JavaRestClient实现文档的CRUD
初始化:
@SpringBootTest
public class HotelDocumentTest {
@Autowired
private IHotelService hotelService;
@Autowired
private RestHighLevelClient client;
@BeforeEach
void setup() {
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.179.128:9200")
));
}
@AfterEach
void tearDown() throws IOException {
this.client.close();
}
}
1. 新增文档
@Test
void testIndexDocument() throws IOException {
Hotel hotel = hotelService.getById(36934L);
HotelDoc hotelDoc = new HotelDoc(hotel);
IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
client.index(request, RequestOptions.DEFAULT);
}
2. 查询文档
@Test
void testGetDocumentById() throws IOException {
GetRequest request = new GetRequest("hotel", "36934");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
String json = response.getSourceAsString();
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println(hotelDoc);
}
3. 删除文档
@Test
void testDeleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest("hotel", "36934");
client.delete(request, RequestOptions.DEFAULT);
}
4. 修改文档
- 全量修改 = 插入数据
- 增量修改 存在修改该字段,不存在则自动添加字段
@Test
void testUpdateDocument() throws IOException {
UpdateRequest request = new UpdateRequest("hotel", "36934");
request.doc(
"price", "954",
"startName", "四钻"
);
client.update(request, RequestOptions.DEFAULT);
}
5. 批量导入文档
@Test
void testBulk() throws IOException {
List<Hotel> list = hotelService.list();
BulkRequest request = new BulkRequest();
for (Hotel hotel : list) {
HotelDoc hotelDoc = new HotelDoc(hotel);
request.add(new IndexRequest("hotel")
.id(hotelDoc.getId().toString())
.source(JSON.toJSONString(hotelDoc), XContentType.JSON));
}
client.bulk(request, RequestOptions.DEFAULT);
}
小结: