Update API

Update API #

基于现有文档做部分字段更新或脚本更新。 内部流程:读取当前 _source → 合并修改 → 写入新文档(不是原地修改)。

请求格式 #

POST /<index>/_update/<_id>

路径参数 #

参数必需说明
<index>目标索引
<_id>文档 ID

查询参数 #

参数类型默认值说明
retry_on_conflictint0版本冲突时自动重试次数。适合"计数器累加"等顺序不敏感场景
routingstring自定义路由
timeouttime1m等待主分片可用的超时
refreshstringfalse更新后刷新策略:truefalsewait_for
_sourcestring/booleantrue控制响应中是否返回 _source
_source_includesstring响应中 _source 要包含的字段
_source_excludesstring响应中 _source 要排除的字段
if_seq_nolong乐观并发控制
if_primary_termlong乐观并发控制
wait_for_active_shardsstring活跃分片数量
require_aliasbooleanfalse要求目标必须是别名

注意:Update API 不支持 version / version_type 参数。如需乐观并发控制,请使用 if_seq_no + if_primary_term

请求体字段 #

字段类型说明
docobject要合并的部分文档。与现有 _source 做浅合并
upsertobject当文档不存在时,按此内容创建文档
doc_as_upsertbooleantrue 时,若文档不存在则直接将 doc 作为新文档插入
scriptobject/string使用脚本更新。可以是 inline 脚本字符串或 {"source":"...","lang":"painless","params":{...}} 对象
scripted_upsertbooleantrue 时,无论文档是否存在都执行脚本(结合 upsert 使用)
detect_noopbooleantrue 时(默认),如果 doc 合并后没有实际变化,则不执行写入操作
_sourceobject请求体内的 _source 过滤配置

示例 #

部分更新(doc merge) #

给文档增加 tagsviews 字段:

POST /website/_update/1
{
  "doc": {
    "tags":  ["testing"],
    "views": 0
  }
}

已有字段保持不变,新字段被添加。

脚本更新 #

基于旧值做计算——将 views 加 1:

POST /website/_update/1
{
  "script": {
    "source": "ctx._source.views += params.inc",
    "lang":   "painless",
    "params": { "inc": 1 }
  }
}

向数组追加元素:

POST /website/_update/1
{
  "script": {
    "source": "ctx._source.tags.add(params.new_tag)",
    "lang":   "painless",
    "params": { "new_tag": "search" }
  }
}

脚本适合"简单算子 + 高价值更新"场景。复杂业务逻辑尽量放在上游服务完成。

Upsert(不存在则插入) #

计数器场景,第一次更新时文档可能还不存在:

POST /website/_update/1
{
  "script": {
    "source": "ctx._source.views += 1",
    "lang":   "painless"
  },
  "upsert": {
    "views": 1
  }
}
  • 第一次调用:文档不存在,按 upsert 内容创建,views = 1
  • 后续调用:文档已存在,执行脚本,views 递增

doc_as_upsert #

“文档存在就合并 doc,不存在就把 doc 当新文档插入”:

POST /website/_update/1
{
  "doc": {
    "title": "New title",
    "views": 0
  },
  "doc_as_upsert": true
}

冲突重试 #

顺序不敏感的更新(如页面浏览计数器),可以自动重试:

POST /website/_update/1?retry_on_conflict=5
{
  "script": {
    "source": "ctx._source.views += 1",
    "lang":   "painless"
  }
}

最多自动重试 5 次版本冲突。


参考导航 #

需求参见
按查询批量更新Update by Query
整文档覆盖写入Index API
乐观并发控制并发控制与版本