gremlintinkerpopjanusgraphgremlinpython

Gremlin-Python find all nodes connected by edges


I have a list of node labels as node_labels, where some of these may exist in a graph.

node_labels = ['a', 'b', 'c']

Using this I can get the node labels or associated attributes.

g.V().has_label(*node_labels).to_list()

How can I modify the query so that I get only those node(s) where an edge exists (either incoming or outgoing) between the nodes?


Solution

  • If I understand properly, said another way, you want any vertex with those labels if that vertex connects to another vertex with one those labels:

    g.V().has_label(*node_labels).
      filter(both().has_label(*node_labels))
    

    Here's a working example:

    gremlin> g = TinkerFactory.createModern().traversal()
    ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard]
    gremlin> g.V().hasLabel('person')
    ==>v[1]
    ==>v[2]
    ==>v[4]
    ==>v[6]
    gremlin> g.V().hasLabel('person').where(both().hasLabel('person'))
    ==>v[1]
    ==>v[2]
    ==>v[4]