如果文档尚不存在,是否可以使用更新API创建文档

raz*_*inr 22 elasticsearch

我有一个非常简单的问题:

我想将多个文档更新为elasticsearch.有时文件已经存在但有时却不存在.我不想使用get请求来检查文档是否存在(这会降低我的性能).我想直接使用我的更新请求来直接索引文档,如果它还不存在的话.

我知道在更新文档时我们可以使用upsert创建一个不存在的字段,但这不是我想要的.如果文档不存在,我想索引该文档.我不知道upsert是否可以做到这一点.

你能给我一些解释吗?

提前致谢!

rcl*_*ent 47

这可以使用更新API来实现.它确实要求您定义每个文档的ID,因为更新api需要文档的ID来确定其存在.

给定使用以下文档创建的索引:

PUT /cars/car/1 
{ "color": "blue", "brand": "mercedes" }
PUT /cars/car/2
{ "color": "blue", "brand": "toyota" }
Run Code Online (Sandbox Code Playgroud)

我们可以使用带有以下api调用的更新API来获取您想要的upsert功能.

POST /cars/car/3/_update
{
    "doc": {
        "color" : "brown",
        "brand" : "ford"
    },
    "doc_as_upsert" : true
}
Run Code Online (Sandbox Code Playgroud)

此api调用将文档添加到索引,因为它不存在.

更改汽车颜色后第二次运行呼叫将更新文档,而不是创建新文档.

POST /cars/car/3/_update
{
    "doc": {
        "color" : "black",
        "brand" : "ford"
    },
    "doc_as_upsert" : true
}
Run Code Online (Sandbox Code Playgroud)

  • 我想根据 name 字段而不是 id 更新记录库。那么可以通过upsert吗? (3认同)
  • "doc_as_upsert"救了我的命.非常感谢. (2认同)

Ash*_*ynd 6

当您索引文档(使用PUT调用)时,AFAIK会将现有版本替换为较新版本.如果文档不存在,则会创建它.在ElasticSearch中无需区分INSERT和UPDATE.

更新:根据文档,如果您使用op_type = create或索引调用的特殊_create版本,则对已存在的文档的任何调用都将失败.

从文档中引用:

Here is an example of using the op_type parameter:

$ curl -XPUT 'http://localhost:9200/twitter/tweet/1?op_type=create' -d '{
    "user" : "kimchy",
    "post_date" : "2009-11-15T14:12:12",
    "message" : "trying out Elasticsearch"
}'
Another option to specify create is to use the following uri:

$ curl -XPUT 'http://localhost:9200/twitter/tweet/1/_create' -d '{
    "user" : "kimchy",
    "post_date" : "2009-11-15T14:12:12",
    "message" : "trying out Elasticsearch"
}'
Run Code Online (Sandbox Code Playgroud)