我有一個樹形數據結構,其中的數據在葉節點處輸入。我想要做的是將這些數據加到樹上,例如對於樹中的任何節點,總結其下的所有數據。將數據彙總到樹形數據結構中(在圖形數據庫中)
有沒有什麼聰明的方法可以使用圖表數據庫?
我有一個樹形數據結構,其中的數據在葉節點處輸入。我想要做的是將這些數據加到樹上,例如對於樹中的任何節點,總結其下的所有數據。將數據彙總到樹形數據結構中(在圖形數據庫中)
有沒有什麼聰明的方法可以使用圖表數據庫?
在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')