【问题标题】:how to check if a node exists in NEO4J with py2neo如何使用py2neo检查NEO4J中是否存在节点
【发布时间】:2014-04-03 18:51:58
【问题描述】:

我想在我的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 } `}

我需要在我的源代码中实现这个算法

【问题讨论】:

    标签: python-2.7 twitter neo4j tweepy py2neo


    【解决方案1】:

    选项 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},
    )
    

    【讨论】:

      【解决方案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
      

      【讨论】:

      • 不是screen_name == node.screen_name,而是screen_name=node.screen_name
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      相关资源
      最近更新 更多