Add vertices to TitanDB Graph in Java
Asked Answered
Q

1

0

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 ?

Quietus answered 20/11, 2015 at 13:16 Comment(0)
E
2

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.

Eirena answered 20/11, 2015 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.