Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a bidirectional edge between two vertices using gremlin?

Tags:

graph

gremlin

What is the best way to create a bidirectional edge between two vertices using gremlin. Is there a direct command which adds the edge or should we add two edges like vertex X -> Vertex Y and vertex Y -> Vertex X?

like image 297
HEART94 Avatar asked Nov 20 '16 01:11

HEART94


People also ask

What are bidirectional edges?

The “bidirectional edges problem” is to find an edge-labeling of an undirected network,G=(V, E), with a source and a sink, such that an edge [u, v] ∈E is labeled (u, v) or (v, u) (or both) depending on the existence of a (simple) path from the source to sink that visits the verticesu andv, in the orderu, v orv, u, ...

How do you create a vertex in Gremlins?

3.1 Adding a Vertex In Gremlin nodes are referred to as “Vertexes”. To add a node/vertex to the graph, you simply use the command addV() on your graph traversal source. For consistency, most people use “g” as their default graph traversal source. To append properties to your your vertex, you add a series of “.


1 Answers

You can add an edge between two vertices and then ignore the direction at query-time by using the both() step. This is how you typically address bidirectional edges in Gremlin.

Let's open the Gremlin Console and create a simple graph where Alice and Bob are friends:

         \,,,/
         (o o)
-----oOOo-(3)-oOOo-----
gremlin> graph = TinkerGraph.open()
gremlin> g = graph.traversal(standard())
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> 
==>null
gremlin> g.addV(label, 'user', 'name', 'Alice').as('alice').addV(label, 'user', 'name', 'Bob').as('bob').addE('friendWith').from('alice').to('bob')
==>e[4][0-friendWith->2]

This creates a graph with two vertices and one edge:

gremlin> g.V()
==>v[0]
==>v[2]
gremlin> g.E()
==>e[4][0-friendWith->2]

Notice how you cannot traverse from the Bob vertex to the Alice vertex in the outgoing direction, but you can traverse in the ingoing direction (first query yields no result).

gremlin> g.V().has('name', 'Bob').out('friendWith')
gremlin> g.V().has('name', 'Bob').in('friendWith')
==>v[0]

Or starting from Alice (second query yields no result), you get the opposite:

gremlin> g.V().has('name', 'Alice').out('friendWith')
==>v[2]
gremlin> g.V().has('name', 'Alice').in('friendWith')

However, you can traverse the graph in both directions with the both() step, and retrieve Alice's friend or Bob's friend.

gremlin> g.V().has('name', 'Alice').both('friendWith')
==>v[2]
gremlin> g.V().has('name', 'Bob').both('friendWith')
==>v[0]

This would also work on more complex graphs with more than two vertices and one friendship relationship. The both() step simply ignores the direction of the edges when attempting to traverse to adjacent vertices.

like image 113
jbmusso Avatar answered Oct 27 '22 13:10

jbmusso