Elasticsearch JS - 未定义变量[x]

时间:2018-02-26 18:27:41

标签: javascript elasticsearch elasticsearch-6

在测试Elasticsearch索引中,我已将文档编入索引,现在我想通过将其length属性设置为100来更新文档。我想通过脚本(通过这是一个简化的例子来说明我的问题)通过elasticsearch包来做到这一点。

client.update({
  index: 'test',
  type: 'object',
  id: '1',
  body: {
    script: 'ctx._source.length = length',
    params: { length: 100 }
  }
})

但是,我收到以下错误:

{
  "error": {
    "root_cause": [
      {
        "type": "remote_transport_exception",
        "reason": "[6pAE96Q][127.0.0.1:9300][indices:data/write/update[s]]"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "failed to execute script",
    "caused_by": {
      "type": "script_exception",
      "reason": "compile error",
      "script_stack": [
        "ctx._source.length = length",
        "                     ^---- HERE"
      ],
      "script": "ctx._source.length = length",
      "lang": "painless",
      "caused_by": {
        "type": "illegal_argument_exception",
        "reason": "Variable [length]is not defined."
      }
    }
  },
  "status": 400
}

即使我在length中添加了body.params.length属性,也会发生这种情况。

使用以下内容:

  • Elasticsearch server v6.1.1
  • Elasticsearch JavaScript客户端v14.1.0

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-update

的文档错误

在他们的例子中,他们提出:

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

事实上,body.script应该是:

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


因此,如果您将脚本更改为:

script: {
  lang: 'painless',
  source: 'ctx._source.length = params.length',
  params: { length: 100 }
}

它应该有效!

您可能想要参考Painless Examples - Updating Fields with Painless页面!