gpt4 book ai didi

arrays - 在Elasticsearch中轻松检索数组的最后一个元素的信息

转载 作者:行者123 更新时间:2023-12-03 01:30:59 33 4
gpt4 key购买 nike

在更新文档(使用更新API)时,我需要提取数组最后输入的元素的字段,然后在将新元素添加到同一数组时使用它。

例如:

{
"_id": "guid",
"timestamp": "time",
"conversation": [
{
"previousTopic": "A",
"currentTopic": "B",
"score": 80
},
{
"previousTopic": "B",
"currentTopic": "C",
"score": 85
}
]
}

现在,在使用更新API将新元素插入此数组的同时,首先提取最后一个元素的“currentTopic”字段(在本例中为C),然后将其作为下一个元素的“previousTopic”插入。

我知道如何使用基本的更新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 }
}
}
}

最佳答案

我能够使用轻松的脚本完美地做到这一点。

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]);

"""
}
}

关于arrays - 在Elasticsearch中轻松检索数组的最后一个元素的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55949689/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com