我在ArangoDB中有一个简单的父子关系。每个父文档可以包含零个到多个子级。假设父文档具有属性pa1,子文档具有一个属性ca1,并且引用返回到“_id_parent”的父_id。如何编写AQL查询以返回如下结果集:
[{
"_key": "111",
"_id": "parent/111",
"pa1": "aaa",
"children": [{
"_key": "21",
"_id": "child/21",
"_id_parent": "parent/111",
"ca1": "www"
},
{
"_key": "22",
"_id": "child/22",
"_id_parent": "parent/111",
"ca1": "xxx"
}
]
},
{
"_key": "222",
"_id": "parent/222",
"pa1": "ddd",
"children": [{
"_key": "31",
"_id": "child/31",
"_id_parent": "parent/222",
"ca1": "yyy"
},
{
"_key": "32",
"_id": "child/32",
"_id_parent": "parent/222",
"ca1": "zzz"
}
]
}
]
换句话说,我如何“扁平化”这个:
FOR p IN Parent
FILTER p.pa1 == @parm1
LET children = (
(FOR c IN Child
FILTER c._id_parent == p._id
RETURN c)
)
RETURN {p, children}
答案 0 :(得分:2)
剩下要做的就是将儿童与父文件实际合并:
RETURN MERGE(p, {children})
这是RETURN MERGE(p, {children: children})
的缩写形式。
p
就是这样:
{
"_id": "Parent/111",
"_key": "111",
"_rev": "_WLsUlK2--_",
"pa1": "aaa"
}
{children}
或更详细的{children: children}
创建一个具有单个属性的对象,其名称为 children ,而children
变量的值为:
{
"children": [
{
"_key": "21",
"_id": "Child/21",
"_rev": "_WLsW4Su--_",
"_id_parent": "Parent/111",
"ca1": "www"
},
{
"_key": "22",
"_id": "Child/22",
"_rev": "_WLsW8Zu--_",
"_id_parent": "Parent/111",
"ca1": "xxx"
}
]
}
MERGE()结合了两个对象。由于属性键没有重叠(" _id"," _key"," _rev"," pa1" vs."儿童"),p
的顶级属性不会被children
取代。
BTW:您可以在子查询表达式周围留出一对括号
LET var = ( ( <subquery> ) )
- 只需LET var = ( <subquery> )
即可。