创建一个新的document(creating a new document)

怎么保证在存储一个document的时候是创建一个新的而不是重写了一个已经存在的document呢?

回想一下,_index,_type,_id联合确定了一个document。所以最简单的方法就是使用post,让ES自动生成一个id。这样保证了id是不重复的。也就保证了每次执行index的时候是create而不是overwriting。

POST /website/blog/
{...}

如果我们执意要使用我们已经有了的一个_id,我们应该告诉ES如果没有相同的_index,_type,_id,那么ES就应该接受我们的index请求,如果已经存在相同的_index,_type,_id就不接受index请求。有两种方式可以做这件事情:

1:使用op_type参数。如

PUT /website/blog/123?op_type=create
{...}

2:使用/_create作为url的结束符

PUT /website/blog/123/_create
{...}

如果请求是成功的创建了一个新的document,ES返回的HTTP元数据是201 Crate。

如果已经存在了一个同样_index,_type,_id的document,ES会返回409 Conflict,还有失败信息,如下:

{
 
"error":"DocumentAlreadyExistsException[[website][4][blog][123]:
             document already exists
]",
 
"status":409
}

 

原文:http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/create-doc.html

posted @ 2014-05-15 16:08  QQ1350995917  Views(482)  Comments(0)    收藏  举报