0

你好,我对 python 中的 neo4j(neo4j-driver) 很陌生。检查节点是否不存在时出现问题,我通过这些代码发送了一些与数据库中的节点不匹配的名称。

from neo4j import GraphDatabase

driver = GraphDatabase.driver('bolt://localhost:7687', auth=(user, pass))
session = driver.session()


def matchNode(name):
   Label = 'SINGLE_NODE'
   return session.run("MATCH (a:"+Label+") WHERE a.name= $name " 
                      "RETURN id(a)", name=name).single().value()

name = 'test'
nodeID = matchNode(name)    
   if nodeID:
      print("Exist")
   else:
      print("Not Exist")

但它会出现这样的错误,因为它没有与 db 中的节点匹配。

Traceback (most recent call last):
  File ".\neo4jdriver.py", line 44, in <module>
    props = matchNode(driver,'test')
  File ".\neo4jdriver.py", line 25, in matchNode
    "RETURN id(a)", name=name).single().value()
AttributeError: 'NoneType' object has no attribute 'value'
Failed to write data to connection Address(host='localhost', port=7687) (Address(host='127.0.0.1', port=7687)); ("0; 'Underlying socket connection gone (_ssl.c:2263)'")
Failed to write data to connection Address(host='localhost', port=7687) (Address(host='127.0.0.1', port=7687)); ("0; 'Underlying socket connection gone (_ssl.c:2263)'")
Failed to write data to connection Address(host='localhost', port=7687) (Address(host='127.0.0.1', port=7687)); ("0; 'Underlying socket connection gone (_ssl.c:2263)'")
Failed to write data to connection Address(host='localhost', port=7687) (Address(host='127.0.0.1', port=7687)); ("0; 'Underlying socket connection gone (_ssl.c:2263)'")
Failed to write data to connection Address(host='localhost', port=7687) (Address(host='127.0.0.1', port=7687)); ("0; 'Underlying socket connection gone (_ssl.c:2263)'")

那么我该如何解决这个问题,如果节点不存在则不返回。谢谢你

4

1 回答 1

0

在 matchNode 函数中,您执行一个 try /except 块,其中 try 返回 session.run 并且 except 返回 None

于 2019-08-03T20:39:39.443 回答