java API是较低级别的。据我所知,没有方便的方法,所以你需要自己编写代码。未经检验的,但你可能得到的想法:
Transaction transaction = graphDb.beginTx();
try {
ReadableIndex<Node> autoNodeIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex();
Node n = autoNodeIndex.get("name", "Neo").getSingle();
Node a = autoNodeIndex.get("name", "The Architect").getSingle();
tx.acquireWriteLock(n);
tx.acquireWriteLock(a);
Boolean created = false;
for(Relationship r : n.getRelationships(MyRels.SPEAKS_WITH) {
if(r.getOtherNode(n).equals(a)) { // put other conditions here, if needed
created = true;
break;
}
}
if(!created) {
n.createRelationshipTo(a, MyRels.SPEAKS_WITH);
}
tx.success();
} finally {
tx.finish();
}
更新的马蒂亚斯的评论
这似乎是好的,但不能创建索引。 – goralsoft
您必须首先在嵌入式配置中设置自动索引... –
这不会是线程安全的,如果有两个事务同时进行,则可能会创建两个关系。如果您希望它成为线程/事务安全的,则手动获取n和a上的锁。 –