In the Cypher Fundamentals course, you learned how to query Neo4j using Cypher.
To run Cypher statements in a Python application, you’ll need the Neo4j Python Driver.
The driver acts as a bridge between your Python code and Neo4j, handling connections to the database and the execution of Cypher queries.
Installing the Driver
To install the driver, use the pip command:
shell
pip install neo4j
Creating a Driver Instance
You start by importing the driver and creating an instance:
Create one Driver instance and share it across your entire application.
Verifying Connectivity
You can verify the connection are correct by calling the verifyConnectivity() method.
python
driver.verify_connectivity()
Verify Connectivity
The verifyConnectivity() method will raise an exception if the connection cannot be made.
Running Your First Query
The execute_query() method executes a Cypher query and returns the results.
python
records, summary, keys = driver.execute_query( # (1)
"RETURN COUNT {()} AS count"
)
# Get the first record
first = records[0] # (2)
# Print the count entry
print(first["count"]) # (3)
What is happening here?
execute_query() runs a Cypher query to get the count of all nodes in the database
records contains a list of the rows returned
Keys from the RETURN clause are accessed using dictionary-style indexing with square brackets ([])
Full driver lifecycle
Once you have finished with the driver, call close() to release any resources held by the driver.
python
driver.close()
You can use with to create an all-in-one solution that will automatically close the driver when the block is exited.
python
with GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USERNAME, NEO4J_PASSWORD)) as driver:
result, summary, keys = driver.execute_query("RETURN COUNT {()} AS count")
Lesson Summary
In this lesson you learned how to install the Neo4j Python Driver, create a Driver instance, verify connectivity to your database, and execute your first Cypher statement.