(Python,Neo4j-driver) - 如何 return none 检查节点是否不存在

(Python,Neo4j-driver) - How return none when check if node does not exist

你好,我是 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")

但它会出现这样的错误,因为它在数据库中没有任何匹配的节点。

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)'")

那么我该如何解决这个问题,如果节点不存在,return none。谢谢

在你的 matchNode 函数中你做了一个 try /except 块,其中 try returns session.run 和 except returns None