选项 1
首先使用.find() 查找节点(假设您使用带有标签的neo4j 2.x):
mynode = list(graph_db.find('mylabel', property_key='screen_name',
property_value='foo'))
检查是否找到了一些想法:
your_target_node = # you didn't specify where your target node comes from
# node found
if len(mynode) > 0:
# you have at least 1 node with your property, add relationship
# iterate if it's possible that you have more than
# one node with your property
for the_node in mynode:
# create relationship
relationship = graph_db.create(
(the_node, "LABEL", your_target_node, {"key": "value"})
)
# no node found
else:
# create the node
the_node, = graph_db.create({"key", "value"})
# create relationship
relationship = graph_db.create(
(the_node, "LABEL", your_target_node, {"key": "value"})
)
选项 2
或者,查看get_or_create_path() 以避免节点查找。但是你必须知道你的节点,你需要一个作为 py2neo 节点实例。如果您总是知道/拥有目标节点并想要创建起始节点,这可能会起作用:
path = one_node_of_path.get_or_create_path(
"rel label", {"start node key": start node value},
)