6

Using tinkerpop blueprints API, what is the best way to find if an edge exists between two vertices? I would like to avoid vertex.getEdges() and iterate until find the right one.

E.g.: Check if v1 is friend of v2

Vertex v1 = g.addVertex(null);
Vertex v2 = g.addVertex(null);
Edge edge = g.addEdge(null, v1, v2, "friends");
Edge edge = g.addEdge(null, v1, v2, "follows");

// Node with lots of edges - Supernode - problem?
List<Edge> edges = new ArrayList<Edge>();
for(Edge edge : g.getVertex(v1.getId()).getEdges(Direction.OUT, "friends")){
   if(edge.getVertex(Direction.IN).getId().equals(v2.getId()){
      edges.add(edge);
  }
}

Should I use Vertex Query?


Via gremlin I could do:

g.v(v1.getID()).outE("friends").inV.filter{it.id == v2.getID}

Neo4j way:

IndexHits<Relationship> relationships = relationshipIndex().get("type", edgeType, node1, node2);

Thanks for the help! I am still new to this.

Ondra Žižka
  • 36,997
  • 35
  • 184
  • 250
Luccas
  • 3,628
  • 5
  • 39
  • 69
  • It seems you're able to fetch it with the core API. Why use the "overhead" of the blueprints API in this case? – tstorms May 02 '13 at 09:31
  • The core API is possible with Neo4j, but with Titan for example, I need to use directly blueprints – Luccas May 02 '13 at 17:33
  • 1
    I think you are on the right track. Use Vertex query and vertex centric indices if possible to improve query times. https://github.com/thinkaurelius/titan/wiki/Vertex-Centric-Indices – stephen mallette May 03 '13 at 12:40
  • I am also looking for something like `graphContext.testIncidence(projectVertex(), archiveVertex, "uses");` – Ondra Žižka Apr 20 '16 at 03:02
  • [Here's the jira](https://issues.apache.org/jira/browse/TINKERPOP-1270). – Ondra Žižka Apr 20 '16 at 03:07
  • Related: [How to remove edge between two vertices?](https://stackoverflow.com/questions/34589215/how-to-remove-edge-between-two-vertices) – blahdiblah Aug 02 '19 at 22:48

4 Answers4

4
gremlin> g.v(1).bothE.as('x').bothV.retain([g.v(3)]).back('x')
Mohamed Taher Alrefaie
  • 14,080
  • 5
  • 41
  • 62
4

The back step as used in the answer by Huangmao Quan is no longer available in Tinkerpop. As I answered already to this question the following request may apply to more recent versions of the tinkerpop stack.

g.V().has('propertykey','value1').outE('thatlabel').as('e').inV().has('propertykey','value2').select('e')
Community
  • 1
  • 1
Christoph Möbius
  • 1,012
  • 1
  • 10
  • 17
1

Try this:

if (g.v(1).out('follows').retain([g.v(2)]).hasNext())
{
    println('v(1) follows v(2)')
}

NOTE: the edge here is unidirectional, i.e. you cannot infer whether v2 follows v1 or not.

Source: https://groups.google.com/forum/#!msg/gremlin-users/Og7Xf8tYbx4/gqBArTw98sAJ

murick
  • 76
  • 6
0
g.V(v1).bothE("edge_label").where(otherV().is(v2)
karrot
  • 93
  • 1
  • 5