[英]how to check if a node exists in NEO4J with py2neo
我想在我的python代碼中插入以下驗證:
{`if (data.screen_name == node.screen_name) THEN {just create new relationship with new text} else {create new node with new relationship to text } `}
我需要在我的源代碼中實現此算法
首先使用.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"})
)
另外,請查看get_or_create_path()以避免查找節點。 但是然后您必須知道您的節點,並且需要一個作為py2neo Node實例。 如果您始終知道/擁有目標節點並想要創建起始節點,則此方法可能會起作用:
path = one_node_of_path.get_or_create_path(
"rel label", {"start node key": start node value},
)
使用最新版本的Py2Neo:
from py2neo import Graph, NodeMatcher
graph = Graph(url) #along with username and password
def nodeExist(lbl, node):
matcher = NodeMatcher(graph)
m = matcher.match(lbl, screen_name == node.screen_name).first()
if m is None:
return False
else:
return True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.