分布式搜索elaticsearch
数据以文档的形式存储,也需要通过java代码进行基础的CRUD操作。
文档操作的基本步骤
1.新增文档
先从mysql数据库中查询到所需要新增的数据后,将其转换为文档类型,再通过client插入。
@Test
void testDocument() throws IOException {
// 根据id查询酒店数据
Hotel hotel = hotelService.getById(61083L);
// 转换为文档类型
HotelDoc hotelDoc = new HotelDoc(hotel);
// 1.准备request对象
IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
// 2.准备JSON文档
request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
// 3.发送请求
client.index(request, RequestOptions.DEFAULT);
}
2.查询文档
@Test
void testDocumentById() throws IOException {
// 1.准备Request
GetRequest request = new GetRequest("hotel", "61083");
// 2.发送请求,得到响应
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 3.解析响应结果
String json = response.getSourceAsString();
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println(hotelDoc);
}
3.更新文档
下方代码展示了局部更新的例子,操作只更新提到的参数,其余未提到的参数保持不变。
@Test
void testUpdateDocument()