18.Elasticsearch更新文档4---局部更新3---restAPI

本文介绍了如何使用Update API来部分更新文档,而不是每次都完全替换文档。通过实际案例演示了如何添加及更新字段,如增加查看次数等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 更新整个文档 , 我们已经介绍过 更新一个文档的方法是检索并修改它,然后重新索引整个文档;然而,使用 update API 我们还可以部分更新文档,例如在某个请求时对计数器进行累加(比如博客的被访问次数)。

前面介绍过文档是不可变的:他们不能被修改,只能被替换。 update API 必须遵循同样的规则。 从外部来看,我们在一个文档的某个位置进行部分更新。然而在内部, update API 还是简单使用 与之前描述相同的:检索-修改-重建索引 的处理过程。 区别在于这个过程发生在分片内部,这样就避免了多次请求的网络开销。通过减少检索和重建索引步骤之间的时间,我们也减少了其他进程的变更带来冲突的可能性。

update 请求最简单的一种形式:是接收文档的一部分作为 doc 的参数, 它只是与现有的文档进行合并。对象被合并到一起,覆盖现有的字段,增加新的字段。

1.我们先查询出一个现有的文档:
GET /policy_document/policy_document/222
{
  "_index": "policy_document",
  "_type": "policy_document",
  "_id": "222",
  "_version": 2,
  "found": true,
  "_source": {
    "level": "国家",
    "plat_from": 11,
    "reference_number": "222new",
    "title": "省级文明单位颁发文件111new号",
    "from_type": 1,
    "id": "111",
    "_id_": "111",
    "launch_date": 1485878400000,
    "launch_department": "国家科技局222new"
  }
}
2.新增一个查看次数的字段
POST policy_document/policy_document/222/_update
{
  "doc": {
    "view_time":1
  }
}

执行后会返回如下信息,我们会看到,版本号发生了变化:

{
  "_index": "policy_document",
  "_type": "policy_document",
  "_id": "222",
  "_version": 3,
  "result": "updated",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  }
}
3.再次查询出这个文档

会发现这个文档里面新增了一个字段

GET /policy_document/policy_document/222
{
  "_index": "policy_document",
  "_type": "policy_document",
  "_id": "222",
  "_version": 3,
  "found": true,
  "_source": {
    "level": "国家",
    "plat_from": 11,
    "reference_number": "222new",
    "title": "省级文明单位颁发文件111new号",
    "from_type": 1,
    "id": "111",
    "_id_": "111",
    "launch_date": 1485878400000,
    "launch_department": "国家科技局222new",
    "view_time": 1
  }
}
4.更改查看次数
POST policy_document/policy_document/222/_update
{
  "doc": {
    "view_time":2
  }
}

返回

{
  "_index": "policy_document",
  "_type": "policy_document",
  "_id": "222",
  "_version": 4,
  "result": "updated",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  }
}
5.查看此文档
GET /policy_document/policy_document/222

会发现查看次数被修改了

{
  "_index": "policy_document",
  "_type": "policy_document",
  "_id": "222",
  "_version": 4,
  "found": true,
  "_source": {
    "level": "国家",
    "plat_from": 11,
    "reference_number": "222new",
    "title": "省级文明单位颁发文件111new号",
    "from_type": 1,
    "id": "111",
    "_id_": "111",
    "launch_date": 1485878400000,
    "launch_department": "国家科技局222new",
    "view_time": 2
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值