我使用py2neo(v 1.9.2)将数据写入neo4j db。
batch = neo4j.WriteBatch(graph_db)
current_relationship_index = graph_db.get_or_create_index(neo4j.Relationship, "Current_Relationship")
touched_relationship_index = graph_db.get_or_create_index(neo4j.Relationship, "Touched_Relationship")
get_rel = current_relationship_index.get(some_key1, some_value1)
if len(get_rel) == 1:
batch.add_indexed_relationship(touched_relationship_index, some_key2, some_value2, get_rel[0])
elif len(get_rel) == 0:
created_rel = current_relationship_index.create(some_key3, some_value3, (my_start_node, "KNOWS", my_end_node))
batch.add_indexed_relationship(touched_relationship_index, some_key4, "touched", created_rel)
batch.submit()
有没有办法用批处理命令替换current_relationship_index.get(..)和current_relationship_index.create(...)?我知道有一个,但问题是,我需要根据这些命令的返回行事。我希望由于性能而批量处理所有陈述。
我已经读过索引关系的情况并不常见,但我这样做的原因如下:我需要每天解析一些(文本)文件,然后需要检查是否有任何关系在前一天发生了变化,即如果文本文件中不存在关系,我想在neo4j中用“替换”属性标记它。因此,我将所有“触摸”关系添加到适当的索引,所以我知道这些没有改变。 touch_relationship_index中没有的所有关系显然不再存在,所以我可以标记它们。
我想不出更简单的方法,即使我确定py2neo提供了一个。
编辑:考虑到奈杰尔的评论,我试过这个:
my_rel = batch.get_or_create_indexed_relationship(current_relationship_index, some_key, some_value, my_start_node, my_type, my_end_node)
batch.add_indexed_relationship(touched_relationship_index, some_key2, some_value2, my_rel)
batch.submit()
这显然不起作用,因为我不能在批处理中引用“my_rel”。我怎么解决这个问题?请参阅前一批处理语句的结果“0”?但是考虑到整个事情应该在循环中运行,所以数字不固定。也许使用一些变量“batch_counter”来引用当前的批处理语句,并且只要将一个语句添加到批处理中,它总是递增的?
答案 0 :(得分:0)
看看WriteBatch.get_or_create_indexed_relationship
。这可以根据当前是否存在并以原子方式运行来有条件地创建关系。文档链接如下:
http://book.py2neo.org/en/latest/batches/#py2neo.neo4j.WriteBatch.get_or_create_indexed_relationship
py2neo中有一些类似的唯一性管理工具,我最近在博客中提到了您可能想要了解的here。