Installing the driver

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:

shell
pip install neo4j

Creating a Driver Instance

You start by importing the driver and creating an instance:

python
from neo4j import GraphDatabase

driver = GraphDatabase.driver(
  "neo4j://localhost:7687",       # (1)
  auth=("neo4j", "your-password") # (2)
)
  1. The connection string for your Neo4j database

  2. 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.

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?

  1. execute_query() runs a Cypher query to get the count of all nodes in the database

  2. records contains a list of the rows returned

  3. 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.

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.