java读titan,在Java中将顶点添加到TitanDB图

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 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值