创建新文档,而不是覆盖现有
1、自动生成唯一_id
POST /website/blog/
{ ... }
2、如果已经有自己的_id
,必须搞ES,只有_index、_type、_id
不存在时才接受创建
使用op_type
查询-字符串参数:
PUT /website/blog/123?op_type=create
{ ... }
在URL末尾使用/_create
PUT /website/blog/123/_create
{ ... }
3、错误时返回结果
409 Conflict
状态码,以及如下信息
{
"error": {
"root_cause": [
{
"type": "document_already_exists_exception",
"reason": "[blog][123]: document already exists",
"shard": "0",
"index": "website"
}
],
"type": "document_already_exists_exception",
"reason": "[blog][123]: document already exists",
"shard": "0",
"index": "website"
},
"status": 409
}
文档的部分更新
1、添加字段(doc只是与现有文档进行合并)
POST /website/blog/1/_update
{
"doc" : {
"tags" : [ "testing" ],
"views": 0
}
}
2、使用脚本部分更新文档
脚本可以在update API
中用来改变_source
的字段内容,它在更新脚本中成为ctx._source
使用脚本来增加views
POST /website/blog/1/_update
{
"script" : "ctx._source.views+=1"
}
可以通过使用脚本给tags
数组添加一个新的标签。其中new_tag
是参数
POST /website/blog/1/_update
{
"script" : "ctx._source.tags+=new_tag",
"params" : {
"new_tag" : "search"
}
}
效果:search
标签添加到tags
数组中,views
字段已递增
{
"_index": "website",
"_type": "blog",
"_id": "1",
"_version": 5,
"found": true,
"_source": {
"title": "My first blog entry",
"text": "Starting to get the hang of this...",
"tags": ["testing", "search"], (1)
"views": 1 (2)
}
}
可以选择通过设置ctx.op
为delete
来删除基于其内容的文档
POST /website/blog/1/_update
{
"script" : "ctx.op = ctx._source.views == count ? 'delete' : 'none'",
"params" : {
"count": 1
}
}
3、更新的文档可能不存在
如果指定文档不存在则应该先创建它
第一次运行时,upsert
作为新文档被索引,初始化views
字段为1
后续运行,script
更新操作将替代upsert
POST /website/pageviews/1/_update
{
"script" : "ctx._source.views+=1",
"upsert": {
"views": 1
}
}
4、更新冲突,设置失败重试次数
POST /website/pageviews/1/_update?retry_on_conflict=5
{
"script" : "ctx._source.views+=1",
"upsert": {
"views": 0
}
}