What is the right way to find an edge between two vertices?
Asked Answered
P

4

8

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.

Proulx answered 1/5, 2013 at 22:19 Comment(6)
It seems you're able to fetch it with the core API. Why use the "overhead" of the blueprints API in this case?Frogmouth
The core API is possible with Neo4j, but with Titan for example, I need to use directly blueprintsProulx
I think you are on the right track. Use Vertex query and vertex centric indices if possible to improve query times. github.com/thinkaurelius/titan/wiki/Vertex-Centric-IndicesKynthia
I am also looking for something like graphContext.testIncidence(projectVertex(), archiveVertex, "uses");Kiwi
Here's the jira.Kiwi
Related: How to remove edge between two vertices?Duumvirate
H
4
gremlin> g.v(1).bothE.as('x').bothV.retain([g.v(3)]).back('x')
Halvorsen answered 6/12, 2014 at 4:21 Comment(0)
M
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')
Mroz answered 27/5, 2016 at 8:49 Comment(0)
I
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

Insurable answered 2/2, 2015 at 21:54 Comment(0)
H
0
g.V(v1).bothE("edge_label").where(otherV().is(v2)
Hopping answered 11/12, 2019 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.