脚本更新,可以对文档进行局部更新,脚本可以在 update API中用来改变 _source 的字段内容, 它在更新脚本中称为 ctx._source 。我们这里尝试用脚本来对_source中的内容来进行更新。
1.查询出一个文档
GET /policy_document/policy_document/222
{
"_index": "policy_document",
"_type": "policy_document",
"_id": "222",
"_version": 6,
"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": 4
}
}
我们可以看到,view_time值为4,我们现在通过脚本来改变他
2.发送脚本来增加访问量view_time
POST policy_document/policy_document/222/_update
{
"script": "ctx._source.view_time+=1"
}
会返回
{
"_index": "policy_document",
"_type": "policy_document",
"_id": "222",
"_version": 7,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
3.再次查询出此文档
会发现:view_time被+1了,而且,每修改一次这个文档,他的版本号都会改变。
GET /policy_document/policy_document/222
{
"_index": "policy_document",
"_type": "policy_document",
"_id": "222",
"_version": 7,
"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": 5
}
}
这是一个简单的修改,下一篇,我们会讲解一种更加常用的操作。