面试题答案
一键面试实现思路
- 确定查询条件:明确嵌套对象中用于判断的条件,比如某个字段的值满足特定要求。
- 定位嵌套路径:找到需要更新的嵌套对象以及目标字段在文档中的嵌套路径。
- 编写脚本:使用Elasticsearch支持的脚本语言(如Painless),根据条件对目标字段进行更新。
脚本示例代码
假设文档结构如下:
{
"main_obj": {
"nested_obj1": [
{
"condition_field": "value1",
"other_field": "original_value"
}
],
"nested_obj2": [
{
"target_field": "old_value"
}
]
}
}
如果要当 nested_obj1
中的 condition_field
为 value1
时,更新 nested_obj2
中的 target_field
为 new_value
,Painless脚本如下:
ctx._source.main_obj.nested_obj2.forEach(
nested2 -> {
ctx._source.main_obj.nested_obj1.forEach(
nested1 -> {
if (nested1.condition_field == "value1") {
nested2.target_field = "new_value";
}
}
);
}
);
在Elasticsearch中执行更新操作时,结合 update
API,示例如下:
POST /your_index/_update/your_doc_id
{
"script": {
"source": "ctx._source.main_obj.nested_obj2.forEach(nested2 -> {ctx._source.main_obj.nested_obj1.forEach(nested1 -> {if (nested1.condition_field == \"value1\") {nested2.target_field = \"new_value\";}});})",
"lang": "painless"
}
}
请根据实际的索引名称、文档ID以及文档结构调整上述代码。