首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Arangodb AQL递归图遍历

Arangodb AQL递归图遍历
EN

Stack Overflow用户
提问于 2016-10-06 13:56:51
回答 2查看 2.5K关注 0票数 3

我有一个有三个集合的图,这些集合可以用边连接。ItemA是itemB的父级,而后者又是itemC的父级。元素只能由方向上的边缘连接。

代码语言:javascript
复制
"_from : child, _to : parent"

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

代码语言:javascript
复制
LET contains = (FOR v IN 1..? INBOUND 'collectionA/itemA' GRAPH 'myGraph' RETURN v)

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

结果如下:

代码语言:javascript
复制
"root": {
    "id": "itemA",
    "contains": [
        {
            "id": "itemB"
        },
        {
            "id": "itemC"
        }
    ]
}

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

代码语言:javascript
复制
"root": {
    "id": "itemA",
    "contains": [
        {
            "id": "itemB",
            "contains": [
                {
                    "id": "itemC"
                }
            }
        ]
    }

那么,我能得到这个运行aql查询的“分层”结果吗?

还有一件事:遍历应该运行,直到遇到叶节点。因此,遍历的深度是未知的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-25 17:36:04

我找到了解决办法。我们决定使用UDF (用户定义函数)。

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

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

在我的例子中: 1)在arango中注册函数。

代码语言:javascript
复制
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:

代码语言:javascript
复制
    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)

注意:在实现您的函数时请不要忘记命名惯例

票数 3
EN

Stack Overflow用户

发布于 2016-10-12 05:25:01

我也需要知道这个问题的答案,所以这里有一个可行的解决方案。

我相信该代码将需要为您定制,并可以做一些改进,请相应地评论,如果适合这个样本的答案。

解决方案是使用Foxx Microservice支持递归并构建树。我遇到的问题是循环路径,但我实现了一个最大深度限制,以阻止这种情况,在下面的示例中硬编码为10。

要创建Foxx微服务:

  1. 创建一个新文件夹(例如递归树)
  2. 创建目录脚本
  3. 将文件manifest.jsonindex.js放在根目录中
  4. 将文件setup.js放在脚本目录中
  5. 然后创建一个包含这三个文件的新zip文件(例如Foxx.zip)
  6. 导航到ArangoDB管理控制台
  7. 单击“服务”/“添加服务”
  8. 输入适当的安装点,例如/my/tree
  9. 单击Zip选项卡
  10. 在您创建的Foxx.zip文件中拖动,它应该没有问题地创建
  11. 如果遇到错误,请确保集合myItemsmyConnections不存在,并且名为myGraph的图形不存在,因为它将尝试用示例数据创建它们。
  12. 然后导航到ArangoDB管理控制台,服务\ /my/tree
  13. 点击API
  14. 展开/树/{rootId}
  15. 提供ItemA的ItemA参数,然后单击“试试看”
  16. 您应该从提供的根id中看到结果。

如果rootId不存在,如果rootId没有子元素,它什么也不返回,它返回一个空数组,如果rootId有循环“包含”值,它返回嵌套到深度限制,我希望有一个更干净的方法来阻止它。

以下是三个文件: setup.js (位于脚本文件夹中):

代码语言:javascript
复制
'use strict';
const db = require('@arangodb').db;
const graph_module =  require("org/arangodb/general-graph");

const itemCollectionName = 'myItems';
const edgeCollectionName = 'myConnections';
const graphName = 'myGraph';

if (!db._collection(itemCollectionName)) {
  const itemCollection = db._createDocumentCollection(itemCollectionName);
  itemCollection.save({_key: "ItemA" });
  itemCollection.save({_key: "ItemB" });
  itemCollection.save({_key: "ItemC" });
  itemCollection.save({_key: "ItemD" });
  itemCollection.save({_key: "ItemE" });

  if (!db._collection(edgeCollectionName)) {
    const edgeCollection = db._createEdgeCollection(edgeCollectionName);
    edgeCollection.save({_from: itemCollectionName + '/ItemA', _to: itemCollectionName + '/ItemB'});
    edgeCollection.save({_from: itemCollectionName + '/ItemB', _to: itemCollectionName + '/ItemC'});
    edgeCollection.save({_from: itemCollectionName + '/ItemB', _to: itemCollectionName + '/ItemD'});
    edgeCollection.save({_from: itemCollectionName + '/ItemD', _to: itemCollectionName + '/ItemE'});
  }

  const graphDefinition = [ 
    { 
      "collection": edgeCollectionName, 
      "from":[itemCollectionName], 
      "to":[itemCollectionName]
    }
  ];

  const graph = graph_module._create(graphName, graphDefinition);
}

mainfest.json (位于根文件夹中):

代码语言:javascript
复制
{
  "engines": {
    "arangodb": "^3.0.0"
  },
  "main": "index.js",
  "scripts": {
    "setup": "scripts/setup.js"
  }
}

index.js (位于根文件夹中):

代码语言:javascript
复制
'use strict';
const createRouter = require('@arangodb/foxx/router');
const router = createRouter();
const joi = require('joi');

const db = require('@arangodb').db;
const aql = require('@arangodb').aql;

const recursionQuery = function(itemId, tree, depth) {
  const result = db._query(aql`
    FOR d IN myItems
    FILTER d._id == ${itemId}
    LET contains = (
      FOR c IN 1..1 OUTBOUND ${itemId} GRAPH 'myGraph' RETURN { "_id": c._id }
    )
    RETURN MERGE({"_id": d._id}, {"contains": contains})
  `);

  tree = result._documents[0];

  if (depth < 10) {
    if ((result._documents[0]) && (result._documents[0].contains) && (result._documents[0].contains.length > 0)) {
        for (var i = 0; i < result._documents[0].contains.length; i++) {
        tree.contains[i] = recursionQuery(result._documents[0].contains[i]._id, tree.contains[i], depth + 1);
        }
    }
  }
  return tree;
}

router.get('/tree/:rootId', function(req, res) {
  let myResult = recursionQuery('myItems/' + req.pathParams.rootId, {}, 0);
  res.send(myResult);
})
  .response(joi.object().required(), 'Tree of child nodes.')
  .summary('Tree of child nodes')
  .description('Tree of child nodes underneath the provided node.');

module.context.use(router);

现在您可以调用端点,只要rootId将返回完整的树。非常快。

ItemA的示例输出如下:

代码语言:javascript
复制
{
  "_id": "myItems/ItemA",
  "contains": [
    {
      "_id": "myItems/ItemB",
      "contains": [
        {
          "_id": "myItems/ItemC",
          "contains": []
        },
        {
          "_id": "myItems/ItemD",
          "contains": [
            {
              "_id": "myItems/ItemE",
              "contains": []
            }
          ]
        }
      ]
    }
  ]
}

您可以看到B项包含两个子项目,ItemC和ItemD,然后ItemD也包含ItemE。

我不能等到ArangoDB AQL改进了FOR v, e, p IN 1..100 OUTBOUND 'abc/def' GRAPH 'someGraph'样式查询中可变深度路径的处理。在3.x中,不推荐使用自定义访问者,但实际上还没有被用于处理路径中顶点深度上的通配符查询或在路径遍历上处理pruneexclude样式命令的强大工具所取代。

如果可以简化的话,希望有评论/反馈。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39897954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档