您的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,
}
}
]
稍后,您将获得有关熊的最新数据:
{
"color": "pink",
"weight": 500,
"diet": "omnivore",
}
所以,你想要更新"颜色"和"体重"熊的价值观,并添加"饮食" "熊"的关键文档。您知道"animal": "bear"
只有一个文档(但您不知道_id):
使用Nodejs驱动程序,updateByQuery语法将更新"熊"具有这些新价值的doc?
(注意:此问题已完全编辑,对SO社区更有用!)
答案 0 :(得分:5)
另一个答案是缺少这一点,因为它没有任何脚本来执行更新。
你需要这样做:
POST /myIndex/myType/_update_by_query
{
"query": {
"term": {
"animal": "bear"
}
},
"script": "ctx._source.color = 'green'"
}
重要说明:
<强>更新强>
你的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)
}
)
答案 1 :(得分:5)
Val在其他SO中提供了答案:
How to update a document based on query using elasticsearch-js (or other means)?
以下是答案:
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)
}
)
答案 2 :(得分:1)
对于elasticsearch 7.4,您可以使用
await client.updateByQuery({
index: "indexName",
body: {
query: {
match: { fieldName: "valueSearched" }
},
script: {
source: "ctx._source.fieldName = params.newValue",
lang: 'painless',
params: {
newValue: "newValue"
}
}
}
});