【博学谷学习记录】超强总结,用心分享 | 第10周:es学习笔记

微服务当中最重要的一环是数据库的查询工作,之前学习的都是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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值