gpt4 book ai didi

recursion - Arangodb AQL递归图遍历

转载 作者:行者123 更新时间:2023-12-04 12:50:17 25 4
gpt4 key购买 nike

我有一个包含三个集合的图形,其中的项目可以通过边连接。ItemA 是 itemB 的父级,而 itemB 又是 itemC 的父级。元素只能由方向上的边连接

"_from : child, _to : parent"

目前我只能通过此 AQL 查询获得“线性”结果:

LET contains = (FOR v IN 1..? INBOUND 'collectionA/itemA' GRAPH 'myGraph' RETURN v)

RETURN {
"root": {
"id": "ItemA",
"contains": contains
}
}

结果是这样的:

"root": {
"id": "itemA",
"contains": [
{
"id": "itemB"
},
{
"id": "itemC"
}
]
}

但我需要得到这样的图遍历的“分层”结果:

"root": {
"id": "itemA",
"contains": [
{
"id": "itemB",
"contains": [
{
"id": "itemC"
}
}
]
}

那么,我可以运行 aql 查询来获得这个“分层”结果吗?

还有一件事:遍历应该一直运行到遇到叶节点为止。所以遍历的深度事先是未知的。

最佳答案

我找到了解决方案。我们决定使用 UDF ( user defined functions )。

以下是构建适当层次结构的几个步骤:

  1. 在arango db中注册函数。
  2. 运行您的 aql 查询,构建一个平面结构(顶点和该顶点的对应路径)。并将结果作为 UDF 函数的输入参数传递。这里我的函数只是将每个元素附加到其父元素

以我为例:1) 在arango db中注册函数。

db.createFunction(
'GO::LOCATED_IN::APPENT_CHILD_STRUCTURE',
String(function (root, flatStructure) {
if (root && root.id) {
var elsById = {};
elsById[root.id] = root;

flatStructure.forEach(function (element) {
elsById[element.id] = element;
var parentElId = element.path[element.path.length - 2];
var parentEl = elsById[parentElId];

if (!parentEl.contains)
parentEl.contains = new Array();

parentEl.contains.push(element);
delete element.path;
});
}
return root;
})
);

2) 使用 udf 运行 AQL:

    LET flatStructure = (FOR v,e,p IN 1..? INBOUND 'collectionA/itemA' GRAPH 'myGraph' 
LET childPath = (FOR pv IN p.vertices RETURN pv.id_source)
RETURN MERGE(v, childPath))

LET root = {"id": "ItemA"}

RETURN GO::LOCATED_IN::APPENT_CHILD_STRUCTURE(root, flatStructure)

注意:请不要忘记the naming convention当实现你的功能时。

关于recursion - Arangodb AQL递归图遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39897954/

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