在更新文档(使用更新API)时,我需要提取数组最后输入的元素的字段,然后在将新元素添加到同一数组时使用它。
例如:
{
"_id": "guid",
"timestamp": "time",
"conversation": [
{
"previousTopic": "A",
"currentTopic": "B",
"score": 80
},
{
"previousTopic": "B",
"currentTopic": "C",
"score": 85
}
]
}
现在,在使用更新API将新元素插入此数组的同时,首先提取最后一个元素的“ currentTopic”字段(在本例中为C),然后将其作为下一个元素的“ previousTopic”插入。
我知道如何使用基本的更新API,该API会在文档数组中插入一个新元素:
POST test/_doc/{doc_id}/_update
{
"script" : {
"source": "ctx._source.communication.add(params.newcom)",
"lang": "painless",
"params" : {
"newcomm" : {
"previousTopic": {extracted value will go here}
"currentTopic" : "D"
"score" : 89 }
}
}
}
答案 0 :(得分:0)
我能够使用轻松的脚本完美地做到这一点。
POST test/_doc/nbsadmnsabdmas/_update
{
"script" : {
"lang": "painless",
"source" :
"""
// find the length of array
def count = ctx._source.conversation.length;
// get to the last element and extract
def temp = ctx._source.conversation[count-1].currentTopic;
// add a new element to the array
ctx._source.communication.add(['previousTopic':temp,'currentTopic':'D',
'score':90]);
"""
}
}