Arangodb AQL recursive graph traversal

后端 未结 2 1423
予麋鹿
予麋鹿 2021-01-22 18:57

I have a graph with three collections which items can be connected by edges. ItemA is a parent of itemB which in turn is a parent of itemC. Elements only can be connected by e

2条回答
  •  我在风中等你
    2021-01-22 19:34

    I have found solution. We decided to use UDF (user defined functions).

    Here is a few steps to construct the proper hierarchical structure:

    1. Register the function in arango db.
    2. Run your aql query, that constructs a flat structure (vertex and corresponding path for this vertex). And pass result as input parameter of your UDF function. Here my function just append each element to its parent

    In my case: 1) Register the function in 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) Run AQL with udf:

        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)
    

    Note: Please don't forget the naming convention when implement your functions.

提交回复
热议问题