2016-07-31 64 views
1

我只是试图创建或替换文档,但API文档不清楚如何执行此操作。如何在Elasticsearch中创建或替换文档?

upsert示例显示了一个文件与一counter价值1创建:

client.update({ 
    index: 'myindex', 
    type: 'mytype', 
    id: '777', 
    body: { 
     script: 'ctx._source.counter += 1', 
     upsert: { 
      counter: 1 
     } 
    } 
}, function(error, response) { 
    // ... 
}) 

我不需要增量脚本,所以我尽量只通过自身发送UPSERT,但我得到一个400 Validation Failed: 1: script or doc is missing

client.update({ 
    index: "testindex", 
    type: "testType", 
    id: 1234, 
    body: { 
     upsert: { 
      itworks: true, 
      ok: "oh yeah" 
     } 
    } 
}) 

好吧,让我们尝试一些愚蠢的,包括DOC两次;一旦下doc,如果upsert下有一个,而一旦这大概会取代现有的文件,该文件将被用于否则创建一个新文件:

client.update({ 
    index: "testindex", 
    type: "testType", 
    id: 1234, 
    body: { 
     upsert: { 
      itworks: true, 
      ok: "oh yeah" 
     }, 
     doc: { 
      itworks: true, 
      ok: "oh yeah" 
     } 
    } 
}) 

也就是说实际工作,201创建。 200确定,当我重复一遍用不同的一个替换文档:

client.update({ 
    index: "testindex", 
    type: "testType", 
    id: 1234, 
    body: { 
     upsert: { 
      whatever: "man" 
     }, 
     doc: { 
      whatever: "man" 
     } 
    } 
}) 

但是,当我检查了DOC(client.get({index: "testindex", type: "testType", id: 1234})),我看到的不是替换原有文件,新的文档与它合并。

如何用标准的Node客户端替换Elasticsearch中的文档? HTTP API使它看起来so simple,但我已经尝试了一些在Node客户端中的排列而没有成功。有没有替换命令?我必须删除然后创建吗?

回答

3

在Elasticsearch中,要替换文档,您只需索引具有相同ID的文档并自动替换它。

如果您想要更新文档,您可以执行脚本更新,部分更新或两者。

执行部分文档更新时,您只需

部分文档更新:

client.update({ 
    index: 'myindex', 
    type: 'mytype', 
    id: '1', 
    body: { 
    // put the partial document under the `doc` key 
    doc: { 
     title: 'Updated' 
    } 
    } 
}, function (error, response) { 
    // ... 
}) 

脚本更新:在Elasticsearch

client.update({ 
    index: 'myindex', 
    type: 'mytype', 
    id: '1', 
    body: { 
    script: 'ctx._source.tags += tag', 
    params: { tag: 'some new tag' } 
    } 
}, function (error, response) { 
    // ... 
}); 

更多信息JS documentation

+0

具有相同ID的'create'调用返回409冲突:文档存在,或者版本冲突,如果包含与现有版本不匹配的版本。 –

+2

尝试'索引'而不是'创建' –

+0

就是这样!我从来不会猜到这个词。我在考虑如何在RDBMS中使用它们的索引,它们大多只是一种优化。 –

1

这是一个我总是使用索引而不是创建的原因:

client.index({ 
    "index": 'index-name', 
    "type": 'mapping type', 
    "id": 'id you want to create/replace', 
    'body': JSON.stringify(obj) 
}, function (err, resp) { 
    if (err) { 
     console.error(err['message']) 
    } 
    else { 
     console.log(resp); 
     return resp 
    } 
});