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

Finding all indirectly connected nodes with specific relationship Gremlin

假设我在 Gremlin 中有一个节点的数字 ID.. 与

一起使用
g.V(n_id)

假设这个节点是一个话题。

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

每个问题都可以有关系threadOf

的答案或评论

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

所有关系都是threadOf

Gremlin 可以吗?

您可以通过多种方式使用 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()

上图是一棵树,因此最好 return 将其作为一个树。为此,我们可以使用 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:[]]]]