简体   繁体   中英

What is the Gremlin query that can get me all the vertices either directly or indirectly connected to one specific vertex

I need help with a Gremlin query that can output all the vertices related to one specific vertex A and their cascading related vertices (which means all the vertices related directly or indirectly to A).

For example, in a graph

A -> B -> C
D

Running this query on A will give me B and C.

The solution I have right now is an ugly one:

gV('A').both(); gV('A').both().both();

etc

Any help would be really appreciated.

Your solution isn't ugly; it only lacks a bit of iteration and an exit condition.

Do you require a maximum depth? Depending on the shape of your graph, the query you want to execute could be returning all vertices of that graph.

Assuming a toy modern TinkerGraph created in the Gremlin console:

gremlin> graph = TinkerFactory.createModern()
==>tinkergraph[vertices:6 edges:6]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard]

This query could be helpful:

gremlin> g.V(1).repeat(both().simplePath()).emit().times(3).dedup()
==>v[3]
==>v[2]
==>v[4]
==>v[6]
==>v[5]

"Starting from vertex with id=1, traverse the graph in all directions up to a maximum depth of 3 while discarding previously visited paths. The emit() step ensures that all traversed vertices found along the way, and not just leaves, are returned."

Chances are high that you want to figure out which vertices are linked to that vertex only via specific edges. In such case, you could be passing label(s) to the both() step, and/or maybe chain a few filters.

When developing your query, feel free to chain the path() step to better understand the output.

gremlin> g.V(1).repeat(both().simplePath()).emit().times(3).dedup().path()
==>[v[1],v[3]]
==>[v[1],v[2]]
==>[v[1],v[4]]
==>[v[1],v[3],v[6]]
==>[v[1],v[4],v[5]]

There are other ways to solve this, but this query should get you started and familiarize yourself with basic Gremlin steps and concepts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM