简体   繁体   中英

Add vertices to TitanDB Graph in Java

The examples from the tutorials or the online documentations often use the Gremlin/Groovy shell to demonstrate the TitanDB APIs. I'm working in plain (old, but not so old) Java-8, and the first thing I need to implement is an efficient method to add vertices and edges to a graph.

So, to getOrCreate a vertex with a String identifier, I did this:

private Vertex getOrCreate(TitanGraph g, String vertexId) {
    Iterator<Vertex> vertices = g.vertices();
    if (!vertices.hasNext()) { // empty graph?
        Vertex v = g.addVertex("id", vertexId);
        return v;
    } else
        while (vertices.hasNext()) {
            Vertex nextVertex = vertices.next();
            if (nextVertex.property("id").equals(vertexId)) {
                return nextVertex;
            } else {
                Vertex v = g.addVertex("id", vertexId);
                return v;
            }
        }
    return null;
}

Is this the most efficient technique offered by the TitanDB APIs ?

First of all, there is no real separation any more between Gremlin Java and Groovy. You can write Gremlin equally well in both. So with that, I'd say, just use Gremlin for your getOrCreate which comes down to a basic one liner:

gremlin> graph = TinkerFactory.createModern()
==>tinkergraph[vertices:6 edges:6]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard]
gremlin> g.V(1).tryNext().orElseGet{graph.addVertex(id, 1)}
==>v[1]

The above code is Groovy syntax, but the Java is pretty much the same:

g.V(1).tryNext().orElseGet(() -> graph.addVertex(id, 1));

The only difference is the lambda/closure syntax. Note that in my case id is the reserved property of Element - it's unique identifier. You might consider a different name for your "identifier" than "id" - perhaps "uniqueId" in which case your getOrCreate will look like this:

private Vertex getOrCreate(TitanGraph graph, String vertexId) {
    GraphTraversalSource g = graph.traversal();
    return g.V().has("uniqueId", vertexId).tryNext().orElseGet(() -> graph.addVertex("uniqueId", vertexId);
}

I'd also recommend passing around the GraphTraversalSource if you can - no need to keep creating that over and over with the graph.traversal() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM