我有一个树形数据结构,其中的数据在叶节点处输入。我想要做的是将这些数据加到树上,例如对于树中的任何节点,总结其下的所有数据。将数据汇总到树形数据结构中(在图形数据库中)
有没有什么聪明的方法可以使用图表数据库?
我有一个树形数据结构,其中的数据在叶节点处输入。我想要做的是将这些数据加到树上,例如对于树中的任何节点,总结其下的所有数据。将数据汇总到树形数据结构中(在图形数据库中)
有没有什么聪明的方法可以使用图表数据库?
在CYPHER(Neo4j的),你可以做这样的事情:
start n=node:node_auto_index(id={id})
match n-[:parent_of*]->child
where not(child-[:parent_of]->()) // where the child doesn't have children (leaf)
return n, sum(child.val);
http://wes.skeweredrook.com/cypher-summing-data-up-a-tree-leaf-nodes/
下面是使用的Gremlin和刚刚杀出aureliusgraphs邮件列表上树数据样本的解决方案:
g = new TinkerGraph()
root = g.addVertex(['name':'root'])
c1 = g.addVertex(['name':'1', 'sortIndex':1])
c11 = g.addVertex(['name':'1.1', 'sortIndex':1])
c12 = g.addVertex(['name':'1.2', 'sortIndex':2])
c121 = g.addVertex(['name':'1.2.1','sortIndex':1])
c122 = g.addVertex(['name':'1.2.2','sortIndex':2])
c13 = g.addVertex(['name':'1.3', 'sortIndex':3])
c2 = g.addVertex(['name':'2', 'sortIndex':2])
c21 = g.addVertex(['name':'2.1', 'sortIndex':1])
c22 = g.addVertex(['name':'2.2', 'sortIndex':2])
c3 = g.addVertex(['name':'3', 'sortIndex':3])
c31 = g.addVertex(['name':'3.1', 'sortIndex':1])
c32 = g.addVertex(['name':'3.2', 'sortIndex':2])
g.addEdge(root, c1, 'has')
g.addEdge(root, c2, 'has')
g.addEdge(root, c3, 'has')
g.addEdge(c1, c11, 'has')
g.addEdge(c1, c12, 'has')
g.addEdge(c1, c13, 'has')
g.addEdge(c2, c21, 'has')
g.addEdge(c2, c22, 'has')
g.addEdge(c3, c31, 'has')
g.addEdge(c3, c32, 'has')
g.addEdge(c12, c121, 'has')
g.addEdge(c12, c122, 'has')
上面的代码初始化图应该很好地粘贴到Gremlin提示。一旦图形被建立,简单地发出此命令遍历树,总结的数值(在此情况下sortIndex字段):
gremlin> total=0;root.out.sideEffect{total+=it.sortIndex}.loop(2){true}
gremlin> total
==>21
上面的代码初始化total
变量,然后从root
开始遍历顶点,遍历出来,然后将sortIndex
字段的值加到总数中。然后它在树上循环/重复该操作直到它耗尽它(最后的true
控制它循环的时间)。
我用TinkerGraph为了方便,但是这个代码将与Neo4j的或OrientDB工作(我看到那些其他的标签在这个问题上),通过简单地改变图形执行如下命令:
g = new Neo4jGraph('/tmp/neo4j')
或
g = new OrientGraph('memory:/graph')