查找具有特定关系的所有间接连接的节点Gremlin

Gre*_*ory 2 graph-databases gremlin gremlin-server janusgraph

假设我在Gremlin中使用了Node的数字ID

g.V(n_id)
Run Code Online (Sandbox Code Playgroud)

说这个节点是一个主题.

每个主题都可以有一个关系问题threadOf.

每个问题都可以有关系的答案或评论 threadOf

如果我得到一个数字ID作为输入,我想要一个gremlin查询,它返回与该主题相关的所有问题以及与这些问题相关的所有答案或评论

所有关系都是 threadOf

Gremlin有可能吗?

ste*_*tte 6

Gremlin有几种方法可以做到这一点.让我们假设这个图形(使用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()
Run Code Online (Sandbox Code Playgroud)

上图是一棵树,因此最好将其作为一个树返回.为此,我们可以使用树步.主题在顶点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:[]]]]
Run Code Online (Sandbox Code Playgroud)

这是有效的,但它假设我们知道"threadOf"边缘树的深度(我们out()从顶点"0"开始两步.如果我们不知道深度我们可以做到:

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