POST

创建新文档,而不是覆盖现有

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.opdelete来删除基于其内容的文档

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
   }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容