Index API

Index API #

将一个 JSON 文档写入指定索引。若文档 ID 已存在,则整文档覆盖并递增 _version

请求格式 #

PUT /<index>/_doc/<_id>
POST /<index>/_doc/<_id>
POST /<index>/_doc            # 自动生成 _id

仅创建(文档存在时返回 409 Conflict):

PUT /<index>/_create/<_id>
POST /<index>/_create/<_id>

路径参数 #

参数必需说明
<index>目标索引名称
<_id>文档 ID。使用 POST /<index>/_doc 时可省略,由系统自动生成

查询参数 #

参数类型默认值说明
op_typestringindex写入类型。index = 创建或覆盖;create = 仅创建(已存在时返回 409)。使用 _create 端点时强制为 create
routingstring自定义路由值,决定文档落入哪个分片
pipelinestring写入前执行的 Ingest Pipeline 名称
refreshstringfalse写入后是否刷新。true = 立即刷新;wait_for = 等待下一次自动刷新完成后返回;false = 不等待
timeouttime1m等待主分片可用的超时时间
versionlong用于外部版本控制的版本号
version_typestringinternal版本类型:internalexternalexternal_gte
if_seq_nolong乐观并发控制:仅当文档的 _seq_no 等于此值时才执行写入
if_primary_termlong乐观并发控制:仅当文档的 _primary_term 等于此值时才执行写入
wait_for_active_shardsstring1写入前需要的活跃分片数量。1 = 仅主分片;all = 全部分片
require_aliasbooleanfalsetrue 时要求 <index> 必须是别名,否则返回错误

请求体 #

完整的 JSON 文档,即 _source 的内容。

示例 #

指定 ID 写入 #

PUT /website/_doc/123
{
  "title": "My first blog entry",
  "text":  "Just trying this out...",
  "date":  "2014/01/01"
}

响应:

{
  "_index":   "website",
  "_type":    "_doc",
  "_id":      "123",
  "_version": 1,
  "result":   "created",
  "_shards": {
    "total":      2,
    "successful": 1,
    "failed":     0
  },
  "_seq_no":       0,
  "_primary_term": 1
}

再次 PUT 同一 _id 会覆盖旧文档:result 变为 "updated"_version 递增。

实现细节:更新不是原地改写,而是将旧文档标记删除,再写入一条新文档。后台通过段合并(segment merge)彻底清理旧版本。

自动生成 ID #

POST /website/_doc
{
  "title": "My second blog entry",
  "text":  "Still trying this out...",
  "date":  "2014/01/01"
}

响应中 _id 由系统生成(URL 安全、全局唯一):

{
  "_index":   "website",
  "_type":    "_doc",
  "_id":      "AVFgSgVHUP18jI2wRx0w",
  "_version": 1,
  "result":   "created"
}

自动 ID 无法保证幂等写入。如果请求超时后重试,可能会产生两条不同 _id 的重复文档。需要幂等语义时请自行指定 _id

仅创建(禁止覆盖) #

PUT /website/_doc/123?op_type=create
{ "title": "My first blog entry" }

或等价写法:

PUT /website/_doc/123/_create
{ "title": "My first blog entry" }
  • 文档不存在 → 201 Created
  • 文档已存在 → 409 Conflict,原文档不受影响

适用场景:日志/事件流、财务流水等"只允许插入不允许覆盖"的业务。


参考导航 #

需求参见
按 ID 检索文档Get API
部分更新文档Update API
批量写入Bulk API
写入的分布式协调分布式写入过程
乐观并发控制并发控制与版本