微服务当中最重要的一环是数据库的查询工作,之前学习的都是SQL来查询MySql数据库,但是做全文搜索时,查询的效率太低,这时候就可以使用es(elastic search)来代替。
这里简单总结一下es的CRUD操作。
新增文档
POST /索引库名/_doc/文档id
{
"字段1": "值1",
"字段2": "值2",
"字段3": {
"子属性1": "值3",
"子属性2": "值4"
},
// ...
}
示例
POST /heima/_doc/1
{
"info": "test",
"email": "zy@163.cn",
"name": {
"firstName": "zhao",
"lastName": "yun"
}
}
查询文档
GET /{索引库名称}/_doc/{id}
示例
GET /heima/_doc/1
删除文档
DELETE /{索引库名}/_doc/id值
示例(根据id删除)
DELETE /heima/_doc/1
修改文档
全量修改
PUT /{索引库名}/_doc/文档id
{
"字段1": "值1",
"字段2": "值2",
// ... 略
}
示例
PUT /heima/_doc/1
{
"info": "黑马程序员高级Java讲师",
"email": "zy@itcast.cn",
"name": {
"firstName": "云",
"lastName": "赵"
}
}
增量修改
POST /{索引库名}/_update/文档id
{
"doc": {
"字段名": "新的值",
}
}
示例
POST /heima/_update/1
{
"doc": {
"email": "ZhaoYun@itcast.cn"
}
}
RestAPI
创建索引
@Test
void createHotelIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("hotel");
request.source(MAPPING_TEMPLATE, XContentType.JSON);
client.indices().create(request, RequestOptions.DEFAULT);
}
删除索引
@Test
void testDeleteHotelIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("hotel");
client.indices().delete(request, RequestOptions.DEFAULT);
}
新增文档
@Test
void testAddDocument() throws IOException {
Hotel hotel = hotelService.getById(61083L);
HotelDoc hotelDoc = new HotelDoc(hotel);
String json = JSON.toJSONString(hotelDoc);
IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
request.source(json, XContentType.JSON);
client.index(request, RequestOptions.DEFAULT);
}
查询文档
@Test
void testGetDocumentById() throws IOException {
GetRequest request = new GetRequest("hotel", "61082");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
String json = response.getSourceAsString();
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println(hotelDoc);
}
删除文档
@Test
void testDeleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest("hotel", "61083");
client.delete(request, RequestOptions.DEFAULT);
}
@Test
void testUpdateDocument() throws IOException {
UpdateRequest request = new UpdateRequest("hotel", "61083");
request.doc(
"price", "952",
"starName", "四钻"
);
client.update(request, RequestOptions.DEFAULT);
}