更新
编辑更新编辑
更新 API 允许使用给定的脚本更新特定文档。在以下示例中,我们将索引一个文档,该文档还跟踪角色说出给定引语的次数,然后我们将更新 times
字段。
'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '<cloud-id>' }, auth: { apiKey: 'base64EncodedKey' } }) async function run () { await client.index({ index: 'game-of-thrones', id: '1', document: { character: 'Ned Stark', quote: 'Winter is coming.', times: 0 } }) await client.update({ index: 'game-of-thrones', id: '1', script: { lang: 'painless', source: 'ctx._source.times++' // you can also use parameters // source: 'ctx._source.times += params.count', // params: { count: 1 } } }) const document = await client.get({ index: 'game-of-thrones', id: '1' }) console.log(document) } run().catch(console.log)
使用更新 API,您还可以对文档进行部分更新。
'use strict' const { Client } = require('@elastic/elasticsearch') const client = new Client({ cloud: { id: '<cloud-id>' }, auth: { apiKey: 'base64EncodedKey' } }) async function run () { await client.index({ index: 'game-of-thrones', id: '1', document: { character: 'Ned Stark', quote: 'Winter is coming.', isAlive: true } }) await client.update({ index: 'game-of-thrones', id: '1', doc: { isAlive: false } }) const document = await client.get({ index: 'game-of-thrones', id: '1' }) console.log(document) } run().catch(console.log)