Greg Peckory
Greg Peckory

Reputation: 8068

Finding all indirectly connected nodes with specific relationship Gremlin

Suppose I have the numerical ID of a Node in Gremlin.. utilized with

g.V(n_id)

Say this Node is a topic.

Each topic can have a question with relationship threadOf.

Each question can have an answer or comment with relationship threadOf

If I get a numerical ID as an input I'd like a gremlin query which returns all the questions related to this topic and all the answers or comments related to those questions

All relationships are threadOf

Is this possible with Gremlin?

Upvotes: 2

Views: 1191

Answers (1)

stephen mallette
stephen mallette

Reputation: 46226

There are a few ways you can do this with Gremlin. Let's assume this graph (with Gremlin questions it is always helpful to include a small graph sample in the question itself like this):

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()

The graph above is a tree so it might be best to return it as one. To do this we can use tree step. The topic is at vertex id "0" so if we want all of the "threadOf" hierarchy we could just do:

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

That works, but it assumes we know the depth of the tree of "threadOf" edges (we step out() twice from vertex "0". If we don't know the depth we can do:

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

Upvotes: 6

Related Questions