在Java中将顶点添加到TitanDB图 [英] Add vertices to TitanDB Graph in Java

查看:114
本文介绍了在Java中将顶点添加到TitanDB图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

教程或在线文档中的示例经常使用Gremlin/Groovy shell来演示TitanDB API. 我正在使用普通的(旧的,但不是很旧的)Java-8,而我需要实现的第一件事是一种向图添加顶点和边的有效方法.

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.

所以,要使用字符串标识符getOr创建一个顶点,我这样做了:

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;
}

这是TitanDB API提供的最有效的技术吗?

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

推荐答案

首先,Gremlin Java和Groovy之间不再存在真正的分离.您可以在两者中同样出色地编写Gremlin.因此,我想说的是,只需对您的getOrCreate使用Gremlin,这将归结为一个基本的衬里:

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]

上面的代码是Groovy语法,但是Java几乎相同:

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

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

唯一的区别是lambda/closure语法.请注意,在我的情况下,idElement的保留属性-它是唯一标识符.您可能会为标识符"考虑一个与"id"不同的名称-也许是"uniqueId",在这种情况下,您的getOrCreate看起来像这样:

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);
}

如果可以的话,我也建议绕过GraphTraversalSource-无需继续使用graph.traversal()方法来重复创建.

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.

这篇关于在Java中将顶点添加到TitanDB图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆