Connection
Once you have installed the driver and have a running Neo4j instance, you are ready to connect your application to the database.
Connect to the database
You connect to a database by creating a Driver object and providing a URL and your login credentials.
from neo4j import GraphDatabase
# URI examples: "neo4j://localhost", "neo4j+s://xxx.databases.neo4j.io"
URI = "<database-uri>"
AUTH = ("<username>", "<password>")
with GraphDatabase.driver(URI, auth=AUTH) as driver: (1)
driver.verify_connectivity() (2)
print("Connection established.")
| 1 | Creating a Driver instance only provides information on how to access the database, but does not actually establish a connection.
Connection is instead deferred to when the first query is executed. |
| 2 | To verify immediately that the driver can connect to the database (valid credentials, compatible versions, etc), use the .verify_connectivity() method after initializing the driver.
In case of failure, enabling the driver’s logs can help diagnosing the issue. |
Both the creation of a Driver object and the connection verification can raise a number of different exceptions.
Since error handling can get quite verbose, and a connection error is a blocker for any subsequent task, a common choice is to let the program crash should an exception occur during connection.
Driver objects are immutable, thread-safe, and expensive to create, so your application should create only one instance and pass it around (you can share Driver instances across threads).
If you need to query the database through several different users, use impersonation without creating a new Driver instance.
If you want to alter a Driver configuration, you need to create a new object.
| The driver also supports other authentication methods (kerberos, bearer, custom). |
Connect to an Aura instance
When you create an Aura instance, you get to download a text file (a so-called Dotenv file) containing the connection information to the database as environment variables.
The file has a name of the form Neo4j-a0a2fa1d-Created-2023-11-06.txt.
You can either manually extract the URI and the credentials from that file, or use a third party-package (ex. python-dotenv) to load them.
import dotenv
import os
from neo4j import GraphDatabase
load_status = dotenv.load_dotenv("Neo4j-a0a2fa1d-Created-2023-11-06.txt")
if load_status is False:
raise RuntimeError('Environment variables not loaded.')
URI = os.getenv("NEO4J_URI")
AUTH = (os.getenv("NEO4J_USERNAME"), os.getenv("NEO4J_PASSWORD"))
with GraphDatabase.driver(URI, auth=AUTH) as driver:
driver.verify_connectivity()
print("Connection established.")