如何在Elasticsearch中创建或替换文档?

Dan*_*oss 2 javascript node.js elasticsearch

我只是尝试创建或替换文档,但是API文档尚不清楚如何执行此操作。

所述UPSERT示例示出了一个文件都与创建counter的值1

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

我不需要增量脚本,因此我尝试自己发送一个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"
         }
     }
 })
Run Code Online (Sandbox Code Playgroud)

好吧,让我们尝试一些愚蠢的事情,并将文档添加两次;在之下doc,可能会替换现有文档(如果有的话);在之下upsert,则会用于创建新文档,否则:

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

实际可行,创建了201。当我重复将其替换为另一文档时,返回200 OK:

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

但是,当我检查doc(client.get({index: "testindex", type: "testType", id: 1234}))时,我发现与替换现有文档相反,新文档已与其合并。

您如何用标准的Node客户端替换Elasticsearch中的文档?HTTP API使它看起来如此简单,但是我在Node客户端中尝试了一堆排列,但没有成功。没有替换命令吗?我必须先删除然后再创建吗?

Or *_*ger 5

在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) {
  // ...
})
Run Code Online (Sandbox Code Playgroud)

脚本更新:

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

Elasticsearch JS文档中的更多信息

  • 尝试使用索引而不是创建 (2认同)

smi*_*hra 5

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

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
    }
});
Run Code Online (Sandbox Code Playgroud)