创建一条初始数据
PUT /test_index/test_type/12
{
"num": 0,
"tags": []
}
内置脚本方式
更新
POST /test_index/test_type/12/_update
{
"script" : "ctx._source.num+=1"
}
查询
GET /test_index/test_type/12
返回结果
{
"_index": "test_index",
"_type": "test_type",
"_id": "12",
"_version": 2,
"found": true,
"_source": {
"num": 1,
"tags": []
}
}
外置脚本方式
建立脚本文件,在elasticsearch的\xxxx\config\scripts\
目录下创建名字为test-add-tags.groovy
的文件
并加入一下内容
ctx._source.tags+=new_tag
执行更新:
POST /test_index/test_type/12/_update
{
"script": {
"lang": "groovy",
"file": "test-add-tags",
"params": {
"new_tag": "tag1"
}
}
}
返回结果
{
"_index": "test_index",
"_type": "test_type",
"_id": "12",
"_version": 3,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
查询
GET /test_index/test_type/12
返回结果:
{
"_index": "test_index",
"_type": "test_type",
"_id": "12",
"_version": 3,
"found": true,
"_source": {
"num": 1,
"tags": [
"tag1"
]
}
}
脚本方式:删除文档
建立脚本文件,在elasticsearch的\xxxx\config\scripts\
目录下创建名字为test-delete-document.groovy
的文件
并加入一下内容
ctx.op = ctx._source.num == count ? 'delete' : 'none'
执行更新:
POST /test_index/test_type/12/_update
{
"script": {
"lang": "groovy",
"file": "test-delete-document",
"params": {
"count": 1
}
}
}
返回结果 (successful = 1 删除成功)
{
"_index": "test_index",
"_type": "test_type",
"_id": "12",
"_version": 3,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
查询
GET /test_index/test_type/12
返回结果:
{
"_index": "test_index",
"_type": "test_type",
"_id": "12",
"found": false
}
脚本方式:更新文档
由于经过上一步的文档删除,id=12 的文档已经被删除.所以使用原始的部分更新(partial update)操作将会报错
POST /test_index/test_type/12/_update
{
"doc": {
"num": 1
}
}
返回结果:
{
"error": {
"root_cause": [
{
"type": "document_missing_exception",
"reason": "[test_type][12]: document missing",
"index_uuid": "cbDotlKxS7arKsfavEZgWQ",
"shard": "1",
"index": "test_index"
}
],
"type": "document_missing_exception",
"reason": "[test_type][12]: document missing",
"index_uuid": "cbDotlKxS7arKsfavEZgWQ",
"shard": "1",
"index": "test_index"
},
"status": 404
}
进一步使用脚本方式改进:如果指定的document不存在,就执行upsert中的初始化操作;如果指定的document存在,就执行doc或者script指定的partial update操作
POST /test_index/test_type/12/_update
{
"script" : "ctx._source.num+=1",
"upsert": {
"num": 0,
"tags": []
}
}
返回结果:
{
"_index": "test_index",
"_type": "test_type",
"_id": "12",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}