如何在无痛脚本中深度克隆对象字段
How to deep clone a Object field in painless script
我想在更新对象字段时创建一个新字段来存储旧值。
原文档为:
{
"_index" : "test",
"_id" : "15895_-1",
"_source" : {
"device" : {
"standard": {
"name" : "unknown",
"brand" : "unknown"
},
"other": "other"
}
}
}
这是我的 updateByquery 代码:
GET test/_update_by_query
{
"script": {
"source": """
if (params.deviceStandard != null) {
ctx._source['device_algoed'] = ctx._source['device'];
ctx._source['device']['standard']['series'] = params.deviceStandard.series;
ctx._source['device']['standard']['brand'] = params.deviceStandard.brand;
}
""",
"params": {
"deviceStandard": {
"series" : "unknown",
"brand" : "OPPO"
}
}
},
"query": {
"bool": {
"filter": {
"term": {
"_id": "15895_-1"
}
}
}
}
}
当我更改 ctx._source['device']['standard']
时,ctx._source['device_algoed']
也会更改。
那么如何将 ctx._source['device']['standard']
深度克隆到
ctx._source['device_algoed']
?
你可以做的是从原始地图创建一个新地图:
ctx._source['device_algoed'] = [:];
ctx._source['device_algoed'].putAll(ctx._source['device']);
然后可以自由修改ctx._source['device']
而不影响ctx._source['device_algoed']
就是这样!
我想在更新对象字段时创建一个新字段来存储旧值。
原文档为:
{
"_index" : "test",
"_id" : "15895_-1",
"_source" : {
"device" : {
"standard": {
"name" : "unknown",
"brand" : "unknown"
},
"other": "other"
}
}
}
这是我的 updateByquery 代码:
GET test/_update_by_query
{
"script": {
"source": """
if (params.deviceStandard != null) {
ctx._source['device_algoed'] = ctx._source['device'];
ctx._source['device']['standard']['series'] = params.deviceStandard.series;
ctx._source['device']['standard']['brand'] = params.deviceStandard.brand;
}
""",
"params": {
"deviceStandard": {
"series" : "unknown",
"brand" : "OPPO"
}
}
},
"query": {
"bool": {
"filter": {
"term": {
"_id": "15895_-1"
}
}
}
}
}
当我更改 ctx._source['device']['standard']
时,ctx._source['device_algoed']
也会更改。
那么如何将 ctx._source['device']['standard']
深度克隆到
ctx._source['device_algoed']
?
你可以做的是从原始地图创建一个新地图:
ctx._source['device_algoed'] = [:];
ctx._source['device_algoed'].putAll(ctx._source['device']);
然后可以自由修改ctx._source['device']
而不影响ctx._source['device_algoed']
就是这样!