如何使用py2neo检查NEO4J中是否存在节点

时间:2014-03-02 22:41:04

标签: python-2.7 twitter neo4j tweepy 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 } `}

我需要在源代码中实现此算法

2 个答案:

答案 0 :(得分:4)

选项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 Node实例。如果您始终知道/拥有目标节点并且想要创建起始节点,则这可能有效:

path = one_node_of_path.get_or_create_path(
    "rel label",   {"start node key": start node value},
)

答案 1 :(得分:2)

使用最新版本的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