2017-06-16 122 views
1

假設我有一個節點的數值ID中的Gremlin ..與尋找具有特定關係的所有間接連接的節點的Gremlin

g.V(n_id) 

利用說這個節點是一個課題。

每個主題都可以有關係的問題threadOf

每個問題可以有一個答案,或者如果我得到一個數字ID作爲輸入,我想一個小鬼查詢返回所有與此主題相關的問題和所有答案或評論的關係threadOf

評論有關這些問題

所有的關係都是threadOf

這是可能的小鬼?

回答

5

有幾種方法可以用Gremlin做到這一點。讓我們假設該圖(帶小鬼的問題總是有幫助的,包括在問題本身這樣一個小圖樣本):

gremlin> graph = TinkerGraph.open() 
==>tinkergraph[vertices:0 edges:0] 
gremlin> g = graph.traversal() 
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard] 
gremlin> g.addV('topic').property('text','topic').as('t'). 
......1> addV('question').property('text','question 1').as('q1'). 
......2> addV('question').property('text','question 2').as('q2'). 
......3> addV('comment').property('text','comment 1').as('c1'). 
......4> addV('comment').property('text','comment 2').as('c2'). 
......5> addV('answer').property('text','answer 1').as('a1'). 
......6> addV('answer').property('text','answer 2').as('a2'). 
......7> addE('threadOf').from('t').to('q1'). 
......8> addE('threadOf').from('t').to('q2'). 
......9> addE('threadOf').from('q1').to('c1'). 
.....10> addE('threadOf').from('q1').to('c2'). 
.....11> addE('threadOf').from('q1').to('a1'). 
.....12> addE('threadOf').from('q2').to('a2').iterate() 

上圖是一棵樹那麼它可能是最好的,使其恢復爲一體。要做到這一點,我們可以使用tree step。主題是在頂點ID爲「0」,所以,如果我們希望所有的「threadOf」層次的,我們可能只是這樣做:

gremlin> g.V(0L).out('threadOf').out('threadOf').tree().by('text') 
==>[topic:[question 1:[comment 2:[],comment 1:[],answer 1:[]],question 2:[answer 2:[]]]] 

這樣的作品,但它假定我們知道樹的深度「threadOf」邊緣(從頂點「0」分步out()兩次,如果我們不知道的深度,我們可以這樣做:。

gremlin> g.V(0L).repeat(out('threadOf')).emit().tree().by('text') 
==>[topic:[question 1:[comment 2:[],comment 1:[],answer 1:[]],question 2:[answer 2:[]]]] 
+0

感謝非常詳細的解答..當我用'in',而不是第一溶液中的部分作品「out」,正如你所說我不知道​​樹的深度,所以需要使用第二種解決方案,但是當我使用'in'時,我得到了一個意外的令牌錯誤 –

+0

'in'是groovy中的一個保留字所以你需要d用'in()'步驟的靜態導入的類名作爲前綴。換句話說,'g.V(0L).repeat(__。in('threadOf'))。emit()。tree()。​​by('text')' –

+0

令人驚歎!非常感謝 –

相關問題