前期准备:按照前几篇的内容
- 搭建好linux ES环境。
- 创建好java项目引入ES依赖。
- 准备好测试数据 导入mysql之中。
- 在ES中建好与mysql测试表相对应的索引库
操作文档
新增
@Test
void testAddDoc() throws IOException {
/**
* 从mysql中查询结构化的数据对象
*
* 然后将它转换为 ES中的文档数据对象,
*
* ES创建倒排索引 添加数据
* */
Hotel hotelById = hotelService.getById(61083L);
HotelDoc hotelDoc = new HotelDoc(hotelById);
IndexRequest request = new IndexRequest("hotel").id(hotelById.getId().toString());
request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
client.index(request, RequestOptions.DEFAULT);
}
插入成功:
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "61083",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"address" : "自由贸易试验区临港新片区南岛1号",
"brand" : "皇冠假日",
"business" : "滴水湖临港地区",
"city" : "上海",
"id" : 61083,
"location" : "30.890867, 121.937241",
"name" : "上海滴水湖皇冠假日酒店",
"pic" : "https://m.tuniucdn.com/fb3/s1/2n9c/312e971Rnj9qFyR3pPv4bTtpj1hX_w200_h200_c1_t0.jpg",
"price" : 971,
"score" : 44,
"starName" : "五钻"
}
}
查询
和新增同理 查询也很简单 :
这里记得用 GetRequest ,
//需要注意的是,IndexRequest 用于索引文档,
//而 GetRequest 用于检索文档。
//这两个类提供了不同的功能,用于不同的操作。
@Test
void testGetDoc() throws IOException {
GetRequest request = new GetRequest("hotel","61083");
GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);
String json = documentFields.getSourceAsString();
System.out.println(json);
}
更新
这里要注意 之前提过 ES 文档中两种更新: 全量更新和局部更新
@Test
void testUpdateDoc() throws IOException {
UpdateRequest request = new UpdateRequest("hotel","61083");
HashMap<String, Object> map = new HashMap<>();
map.put("starName","四星");
map.put("city","深圳");
request.doc(map);
client.update(request,RequestOptions.DEFAULT);
}
{
"_index" : "hotel",
"_type" : "_doc",
"_id" : "61083",
"_version" : 2,
"_seq_no" : 1,
"_primary_term" : 1,
"found" : true,
"_source" : {
"address" : "自由贸易试验区临港新片区南岛1号",
"brand" : "皇冠假日",
"business" : "滴水湖临港地区",
"city" : "深圳",
"id" : 61083,
"location" : "30.890867, 121.937241",
"name" : "上海滴水湖皇冠假日酒店",
"pic" : "https://m.tuniucdn.com/fb3/s1/2n9c/312e971Rnj9qFyR3pPv4bTtpj1hX_w200_h200_c1_t0.jpg",
"price" : 971,
"score" : 44,
"starName" : "四星"
}
}
更新成功
批量导入
@Test
void testMutilAddDoc() throws IOException {
BulkRequest request = new BulkRequest();
List<Hotel> list = hotelService.list();
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);
}