Search code examples
javacassandratitangremlintinkerpop3

how to create edge between new vertex and existing vertex using Java API in Titan Graph database


{
    Vertex person1 = titanGraph.addVertex(null);
    person1.setProperty("userId", 1);
    person1.setProperty("username", "abc");


    Vertex person2 = titanGraph.addVertex(null);
    person2.setProperty("userId", 2);
    person2.setProperty("username", "bcd");


    Edge knows = titanGraph.addEdge(null, person1, person2, "Knows");
}

I have created two vertex(person1,person2) and edge(“knows”) between them using JavaAPI. After some time, I want to add vertex(person3). How can I create edge(“knows”) between person1 and person3 using JavaAPI? Kindly help me to resolve this problem.


Solution

  • Here is one way using Titan 1.0.0 and Apache TinkerPop 3.0.1 APIs:

     // lookup existing person1 by userId
     GraphTraversalSource g = titanGraph.traversal();
     Vertex person1 = g.V().has("userId", 1).next();
    
     // create person3
     Vertex person3 = titanGraph.addVertex("Person");
     person3.property("userId", 3);
     person3.property("username", "cde");
    
     // create edge from person1 to person3
     Edge knows = person1.addEdge("Knows", person3);
    

    Please refer to the Javadocs for Titan 1.0.0 and Javadocs for TinkerPop 3.0.1. See also this basic Titan + TinkerPop Java example program for more ideas.

    The syntax is different if you are using an older version of Titan, such as 0.5.4, which the code in your question appears to be using. If you are starting a new project, you should be using 1.0.0.