Search code examples
pythonneo4jneo4j-boltneo4j-driver

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


Hello i'm very new for neo4j(neo4j-driver) in python. I have a problem when checking if node not exist, i have sent some name that not have any matched with node in db by these code.

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

but it error like this because it not have any matched with node in 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)'")

So how can i do to solved this problem and return none if node does not exist. thank you


Solution

  • Inside your matchNode function you do a try /except block where try returns session.run and except returns None