寻找Elasticsearch updateByQuery语法示例(节点驱动程序)

Jam*_*sen 8 elasticsearch elasticsearch-2.0

您有一个带有两个文档的Elasticsearch索引:

[
  {
    "_index": "myIndex",
    "_type": "myType",
    "_id": "es1472002807930",
    "_source": {
      "animal": "turtle",
      "color": "green",
      "weight": 20,
    }
  },
  {
    "_index": "myIndex",
    "_type": "myType",
    "_id": "es1472002809463",
    "_source": {
      "animal": "bear",
      "color": "brown"
      "weight": 400,
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

稍后,您将获得有关熊的更新数据:

{
  "color": "pink",
  "weight": 500,
  "diet": "omnivore",
}
Run Code Online (Sandbox Code Playgroud)

因此,您想要更新熊的"颜色"和"重量"值,并将"饮食"键添加到"熊"文档中.你知道只有一个doc "animal": "bear"(但你不知道_id):

使用Nodejs驱动程序,updateByQuery语法会使用这些新值更新"bear"doc吗?

(注意:这个问题已被完全编辑,对SO社区更有用!)

Jam*_*sen 7

答案是由Val在其他SO中提供的:

如何使用Elasticsearch-js(或其他方式)基于查询更新文档?

答案是:

    var theScript = {
        "inline": "ctx._source.color = 'pink'; ctx._source.weight = 500; ctx._source.diet = 'omnivore';"
    }

    client.updateByQuery({ 
           index: myindex,
           type: mytype,
           body: { 
              "query": { "match": { "animal": "bear" } }, 
              "script": theScript
           }
        }, function(err, res) { 
            if (err) { 
               reportError(err) 
            } 
            cb(err, res)
        }
    )
Run Code Online (Sandbox Code Playgroud)


Val*_*Val 5

另一个答案是缺少这一点,因为它没有任何脚本来执行更新.

你需要这样做:

POST /myIndex/myType/_update_by_query
{
  "query": { 
    "term": {
      "animal": "bear"
    }
  },
  "script": "ctx._source.color = 'green'"
}
Run Code Online (Sandbox Code Playgroud)

重要笔记:

  • 您需要确保启用动态脚本以使其正常工作.
  • 如果您使用的是ES 2.3或更高版本,则内置了逐个查询的功能
  • 如果您使用的是ES 1.7.x或以前的版本,则需要安装update-by-query插件
  • 如果你在ES 2.0和2.2之间使用任何东西,那么你没有任何办法一次性完成这项任务,你需要在两个操作中完成.

UPDATE

您的node.js代码应如下所示,您缺少body参数:

    client.updateByQuery({ 
           index: index,
           type: type,
           body: { 
              "query": { "match": { "animal": "bear" } }, 
              "script": { "inline": "ctx._source.color = 'pink'"}
           }
        }, function(err, res) { 
            if (err) { 
               reportError(err) 
            } 
            cb(err, res)
        }
    )
Run Code Online (Sandbox Code Playgroud)