Introduction
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 pip:
Creating a Driver Instance
You start by importing the driver and creating an instance:
-
The connection string for your Neo4j database
-
Your Neo4j username and password
Best Practice
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.
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.
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.
You can use with
to create an all-in-one solution that will automatically close the driver when the block is exited.
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.
For async applications, use the AsyncGraphDatabase
method.
In the next lesson, you will take a quiz to test your knowledge of installing and creating a driver instance.