titangremlintinkerpop3

How to remove edge between two vertices?


I want to remove edge between two vertices, so my code in java tinkerpop3 as below

private void removeEdgeOfTwoVertices(Vertex fromV, Vertex toV,String edgeLabel,GraphTraversalSource g){
        if(g.V(toV).inE(edgeLabel).bothV().hasId(fromV.id()).hasNext()){
            List<Edge> edgeList = g.V(toV).inE(edgeLabel).toList();
            for (Edge edge:edgeList){
                if(edge.outVertex().id().equals(fromV.id())) {
                    TitanGraph().tx();
                    edge.remove();                    
                    TitanGraph().tx().commit();
                    return;//Remove edge ok, now return.
                }
            }
        }
    }

Is there a simpler way to remove edge between two vertices by a direct query to that edge and remove it? Thank for your help.


Solution

  • Here's an example of how to drop edges between two vertices (where you just have the ids of those vertices:

    gremlin> graph = TinkerFactory.createModern()
    ==>tinkergraph[vertices:6 edges:6]
    gremlin> g = graph.traversal()
    ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard]
    gremlin> g.V(1).bothE()
    ==>e[9][1-created->3]
    ==>e[7][1-knows->2]
    ==>e[8][1-knows->4]
    

    For purpose of the example, let's say we want to drop edges between vertex 1 and vertex 2. We could find those with:

    gremlin> g.V(1).bothE().where(otherV().hasId(2))
    ==>e[7][1-knows->2]
    

    and then remove it with:

    gremlin> g.V(1).bothE().where(otherV().hasId(2)).drop()
    gremlin> g.V(1).bothE()
    ==>e[9][1-created->3]
    ==>e[8][1-knows->4]
    

    If you have the actual vertices, then you could just do:

    gremlin> g.V(v1).bothE().where(otherV().is(v2)).drop()
    gremlin> g.V(1).bothE()
    ==>e[9][1-created->3]
    ==>e[8][1-knows->4]
    

    You could re-write your function as:

    private void removeEdgeOfTwoVertices(Vertex fromV, Vertex toV,String edgeLabel,GraphTraversalSource g){
        g.V(fromV).bothE().hasLabel(edgeLabel).where(__.otherV().is(toV)).drop().iterate();
        g.tx().commit();    
    }