Add vertices to TitanDB Graph in Java

浪子不回头ぞ 提交于 2019-12-11 18:08:52

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/33827685/add-vertices-to-titandb-graph-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!