在 更新整个文档 , 我们已经介绍过 更新一个文档的方法是检索并修改它,然后重新索引整个文档;然而,使用 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
}
}