RestClient的使用
先导入Maven坐标,要和elasticsearch和kibana的版本保持一致
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.1</version>
</dependency>
添加一个Index索引
void createHotelIndex() throws IOException {
//创建Request对象
CreateIndexRequest request = new CreateIndexRequest("hotel");
//准备请求参数,DSL语句
request.source(MAPPING_TEMPLATE, XContentType.JSON);
//发送请求
client.indices().create(request, RequestOptions.DEFAULT);
}
删除一个index索引
void DeleteHotelIndex() throws IOException {
//创建对象
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("hotel");
//发送请求
client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
}
判断一个index索引是否存在
void ExitHotel() throws IOException {
GetIndexRequest request=new GetIndexRequest("hotel");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.err.println(exists?"索引已经存在":"索引不存在");
}
初始化
几乎所有的操作都依赖于
RestHighLevelClient
这个对象
private RestHighLevelClient client;
void setRestHighLevelClient(){
this.client=new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://ip:9200")
));
}
//销毁client
@AfterEach
void tearDown() throws IOException {
this.client.close();
}
添加一个doc文档
void testAddDocument() throws IOException {
Hotel hotel = hotelService.getById(61083L);
//转换为文档类型
HotelDoc hotelDoc=new HotelDoc(hotel);
//准备request对象
IndexRequest request=new IndexRequest("hotel").id(hotelDoc.getId().toString());
//准备JSON文档
request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
client.index(request, RequestOptions.DEFAULT);
}
获取一个doc文档
void testGetDocumentById() throws IOException {
//准备请求
GetRequest request=new GetRequest("hotel","61083");
//发送请求,得到响应
GetResponse response = client.get(request, RequestOptions.DEFAULT);
//拿到数据
String json = response.getSourceAsString();
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println(hotelDoc);
}
局部更新文档
void testUpdateDocument() throws IOException {
UpdateRequest request=new UpdateRequest("hotel","61083");
//准备发送请求
request.doc(
"price","123456"
);
//发送请求
client.update(request,RequestOptions.DEFAULT);
}
删除文档
void DeleteDocument() throws IOException {
DeleteRequest request=new DeleteRequest("hotel","61083");
client.delete(request,RequestOptions.DEFAULT);
}
批量添加doc文档
void BulkRequest() throws IOException {
List<Hotel> hotels = hotelService.list();
BulkRequest request=new BulkRequest();
for (Hotel hotel:hotels){
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);
}