API Documentation

GraphDatabase

Driver Construction

The neo4j.Driver construction is done via a classmethod on the neo4j.GraphDatabase class.

class neo4j.GraphDatabase

Accessor for neo4j.Driver construction.

classmethod driver(uri, *, auth=None, **config)

Create a driver.

Parameters:
  • uri (str) – the connection URI for the driver, see URI for available URIs.

  • auth (tuple[str, str] | Auth | None | AuthManager) – the authentication details, see Auth for available authentication details.

  • config – driver configuration key-word arguments, see Driver Configuration for available key-word arguments.

Return type:

Driver

Driver creation example:

from neo4j import GraphDatabase


uri = "neo4j://example.com:7687"
driver = GraphDatabase.driver(uri, auth=("neo4j", "password"))

driver.close()  # close the driver object

For basic authentication, auth can be a simple tuple, for example:

auth = ("neo4j", "password")

This will implicitly create a neo4j.Auth with scheme="basic". Other authentication methods are described under Auth.

with block context example:

from neo4j import GraphDatabase


uri = "neo4j://example.com:7687"
with GraphDatabase.driver(uri, auth=("neo4j", "password")) as driver:
    ...  # use the driver
classmethod bookmark_manager(initial_bookmarks=None, bookmarks_supplier=None, bookmarks_consumer=None)

Create a BookmarkManager with default implementation.

Basic usage example to configure sessions with the built-in bookmark manager implementation so that all work is automatically causally chained (i.e., all reads can observe all previous writes even in a clustered setup):

import neo4j


# omitting closing the driver for brevity
driver = neo4j.GraphDatabase.driver(...)
bookmark_manager = neo4j.GraphDatabase.bookmark_manager(...)

with (
    driver.session(bookmark_manager=bookmark_manager) as session1,
    driver.session(
        bookmark_manager=bookmark_manager,
        default_access_mode=neo4j.READ_ACCESS,
    ) as session2,
):
    result1 = session1.run("<WRITE_QUERY>")
    result1.consume()
    # READ_QUERY is guaranteed to see what WRITE_QUERY wrote.
    result2 = session2.run("<READ_QUERY>")
    result2.consume()

This is a very contrived example, and in this particular case, having both queries in the same session has the exact same effect and might even be more performant. However, when dealing with sessions spanning multiple threads, Tasks, processes, or even hosts, the bookmark manager can come in handy as sessions are not safe to be used concurrently.

Parameters:
  • initial_bookmarks (Bookmarks | Iterable[str] | None) –

    The initial set of bookmarks. The returned bookmark manager will use this to initialize its internal bookmarks.

    Deprecated since version 6.0: Passing raw string bookmarks is deprecated. Use a Bookmarks object instead.

  • bookmarks_supplier (Callable[[], Bookmarks] | None) – Function which will be called every time the default bookmark manager’s method BookmarkManager.get_bookmarks() gets called. The function takes no arguments and must return a Bookmarks object. The result of bookmarks_supplier will then be concatenated with the internal set of bookmarks and used to configure the session in creation. It will, however, not update the internal set of bookmarks.

  • bookmarks_consumer (Callable[[Bookmarks], None] | None) – Function which will be called whenever the set of bookmarks handled by the bookmark manager gets updated with the new internal bookmark set. It will receive the new set of bookmarks as a Bookmarks object and return None.

Returns:

A default implementation of BookmarkManager.

Return type:

BookmarkManager

Added in version 5.0.

Changed in version 5.3: The bookmark manager no longer tracks bookmarks per database. This effectively changes the signature of almost all bookmark manager related methods:

  • initial_bookmarks is no longer a mapping from database name to bookmarks but plain bookmarks.

  • bookmarks_supplier no longer receives the database name as an argument.

  • bookmarks_consumer no longer receives the database name as an argument.

Changed in version 5.8: Stabilized from experimental.

Changed in version 6.0: Deprecated passing raw string bookmarks as initial_bookmarks.

URI

On construction, the scheme of the URI determines the type of neo4j.Driver object created.

Available valid URIs:

  • bolt://host[:port]

  • bolt+ssc://host[:port]

  • bolt+s://host[:port]

  • neo4j://host[:port][?routing_context]

  • neo4j+ssc://host[:port][?routing_context]

  • neo4j+s://host[:port][?routing_context]

uri = "bolt://example.com:7687"
uri = "neo4j://example.com:7687?policy=europe"

Each supported scheme maps to a particular neo4j.Driver subclass that implements a specific behaviour.

URI Scheme

Driver Object and Setting

bolt

BoltDriver with no encryption or with custom encryption configuration, see Driver Configuration.

bolt+ssc

BoltDriver with encryption (accepts self signed certificates).

bolt+s

BoltDriver with encryption (accepts only certificates signed by a certificate authority), full certificate checks.

neo4j

Neo4jDriver with no encryption or with custom encryption configuration, see Driver Configuration.

neo4j+ssc

Neo4jDriver with encryption (accepts self signed certificates).

neo4j+s

Neo4jDriver with encryption (accepts only certificates signed by a certificate authority), full certificate checks.

Note

See also Note on Encryption Configuration to understand how the URI scheme relates to other encryption configuration options.

Auth

To authenticate with Neo4j the authentication details are supplied at driver creation.

The auth token is an object of the class neo4j.Auth containing static details or neo4j.auth_management.AuthManager object.

class neo4j.Auth(scheme, principal, credentials, realm=None, **parameters)

Container for auth details.

Parameters:
  • scheme (str | None) – specifies the type of authentication, examples: “basic”, “kerberos”

  • principal (str | None) – specifies who is being authenticated

  • credentials (str | None) – authenticates the principal

  • realm (str | None) – specifies the authentication provider

  • parameters (Any) – extra key word parameters passed along to the authentication provider

Example:

import neo4j


auth = neo4j.Auth("basic", "neo4j", "password")
class neo4j.auth_management.AuthManager

Abstract base class for authentication information managers.

The driver provides some default implementations of this class in AuthManagers for convenience.

Custom implementations of this class can be used to provide more complex authentication refresh functionality.

Warning

The manager must not interact with the driver in any way as this can cause deadlocks and undefined behaviour.

Furthermore, the manager is expected to be thread-safe.

The token returned must always belong to the same identity. Switching identities using the AuthManager is undefined behavior. You may use session-level authentication for such use-cases.

See also

AuthManagers

Added in version 5.8.

Changed in version 5.12: on_auth_expired was removed from the interface and replaced by handle_security_exception(). The new method is called when the server returns any Neo.ClientError.Security.* error. Its signature differs in that it additionally receives the error returned by the server and returns a boolean indicating whether the error was handled.

Changed in version 5.14: Stabilized from preview.

abstractmethod get_auth()

Return the current authentication information.

The driver will call this method very frequently. It is recommended to implement some form of caching to avoid unnecessary overhead.

Warning

The method must only ever return auth information belonging to the same identity. Switching identities using the AuthManager is undefined behavior. You may use session-level authentication for such use-cases.

Return type:

tuple[str, str] | Auth | None

abstractmethod handle_security_exception(auth, error)

Handle the server indicating authentication failure.

The driver will call this method when the server returns any Neo.ClientError.Security.* error. The error will then be processed further as usual.

Parameters:
  • auth (tuple[str, str] | Auth | None) – The authentication information that was used when the server returned the error.

  • error (Neo4jError) – The error returned by the server.

Returns:

Whether the error was handled (True), in which case the driver will mark the error as retryable (see Neo4jError.is_retryable()).

Return type:

bool

Added in version 5.12.

class neo4j.auth_management.AuthManagers

A collection of AuthManager factories.

Added in version 5.8.

Changed in version 5.12:

Changed in version 5.14: Stabilized from preview.

static static(auth)

Create a static auth manager.

The manager will always return the auth info provided at its creation.

Example:

# NOTE: this example is for illustration purposes only.
#       The driver will automatically wrap static auth info in a
#       static auth manager.

import neo4j
from neo4j.auth_management import AuthManagers


auth = neo4j.basic_auth("neo4j", "password")

with neo4j.GraphDatabase.driver(
    "neo4j://example.com:7687",
    auth=AuthManagers.static(auth)
    # auth=auth  # this is equivalent
) as driver:
    ...  # do stuff
Parameters:

auth (tuple[str, str] | Auth | None) – The auth to return.

Returns:

An instance of an implementation of AuthManager that always returns the same auth.

Return type:

AuthManager

Added in version 5.8.

Changed in version 5.14: Stabilized from preview.

static basic(provider)

Create an auth manager handling basic auth password rotation.

This factory wraps the provider function in an auth manager implementation that caches the provided auth info until the server notifies the driver that the auth info has expired (by returning an error that indicates that the password is invalid).

Note that this implies that the provider function will be called again if it provides wrong auth info, potentially deferring failure due to a wrong password or username.

Warning

The provider function must not interact with the driver in any way as this can cause deadlocks and undefined behaviour.

The provider function must only ever return auth information belonging to the same identity. Switching identities is undefined behavior. You may use session-level authentication for such use-cases.

Example:

import neo4j
from neo4j.auth_management import (
    AuthManagers,
    ExpiringAuth,
)


def auth_provider():
    # some way of getting a token
    user, password = get_current_auth()
    return (user, password)


with neo4j.GraphDatabase.driver(
    "neo4j://example.com:7687",
    auth=AuthManagers.basic(auth_provider)
) as driver:
    ...  # do stuff
Parameters:

provider (Callable[[], tuple[str, str] | Auth | None]) – A callable that provides new auth info whenever the server notifies the driver that the previous auth info is invalid.

Returns:

An instance of an implementation of AuthManager that returns auth info from the given provider and refreshes it, calling the provider again, when the auth info was rejected by the server.

Return type:

AuthManager

Added in version 5.12.

Changed in version 5.14: Stabilized from preview.

static bearer(provider)

Create an auth manager for potentially expiring bearer auth tokens.

This factory wraps the provider function in an auth manager implementation that caches the provided auth info until either the ExpiringAuth.expires_at exceeded or the server notified the driver that the auth info has expired (by returning an error that indicates that the bearer auth token has expired).

Warning

The provider function must not interact with the driver in any way as this can cause deadlocks and undefined behaviour.

The provider function must only ever return auth information belonging to the same identity. Switching identities is undefined behavior. You may use session-level authentication for such use-cases.

Example:

import neo4j
from neo4j.auth_management import (
    AuthManagers,
    ExpiringAuth,
)


def auth_provider():
    # some way of getting a token
    sso_token = get_sso_token()
    # assume we know our tokens expire every 60 seconds
    expires_in = 60

    # Include a little buffer so that we fetch a new token
    # *before* the old one expires
    expires_in -= 10

    auth = neo4j.bearer_auth(sso_token)
    return ExpiringAuth(auth=auth).expires_in(expires_in)


with neo4j.GraphDatabase.driver(
    "neo4j://example.com:7687",
    auth=AuthManagers.bearer(auth_provider)
) as driver:
    ...  # do stuff
Parameters:

provider (Callable[[], ExpiringAuth]) – A callable that provides a ExpiringAuth instance.

Returns:

An instance of an implementation of AuthManager that returns auth info from the given provider and refreshes it, calling the provider again, when the auth info expires (either because it’s reached its expiry time or because the server flagged it as expired).

Return type:

AuthManager

Added in version 5.12.

Changed in version 5.14: Stabilized from preview.

class neo4j.auth_management.ExpiringAuth(auth, expires_at=None)

Represents potentially expiring authentication information.

This class is used with AuthManagers.bearer() and AsyncAuthManagers.bearer().

Parameters:
  • auth (tuple[str, str] | Auth | None) – The authentication information.

  • expires_at (float | None) – Unix timestamp (seconds since 1970-01-01 00:00:00 UTC) indicating when the authentication information expires. If None, the authentication information is considered to not expire until the server explicitly indicates so.

Added in version 5.8.

Changed in version 5.9:

  • Removed parameter and attribute expires_in (relative expiration time). Replaced with expires_at (absolute expiration time).

  • expires_in() can be used to create an ExpiringAuth with a relative expiration time.

Changed in version 5.14: Stabilized from preview.

auth: tuple[str, str] | Auth | None
expires_at: float | None = None
expires_in(seconds)

Return a (flat) copy of this object with a new expiration time.

This is a convenience method for creating an ExpiringAuth for a relative expiration time (“expires in” instead of “expires at”).

>>> import time, freezegun
>>> with freezegun.freeze_time("1970-01-01 00:00:40"):
...     ExpiringAuth(("user", "pass")).expires_in(2)
ExpiringAuth(auth=('user', 'pass'), expires_at=42.0)
>>> with freezegun.freeze_time("1970-01-01 00:00:40"):
...     ExpiringAuth(("user", "pass"), time.time() + 2)
ExpiringAuth(auth=('user', 'pass'), expires_at=42.0)
Parameters:

seconds (float) – The number of seconds from now until the authentication information expires.

Return type:

ExpiringAuth

Added in version 5.9.

Auth Token Helper Functions

Alternatively, one of the auth token helper functions can be used.

neo4j.basic_auth(user, password, realm=None)

Generate a basic auth token for a given user and password.

This will set the scheme to “basic” for the auth token.

Parameters:
  • user (str) – user name, this will set the principal

  • password (str) – current password, this will set the credentials

  • realm (str | None) – specifies the authentication provider

Returns:

auth token for use with GraphDatabase.driver() or AsyncGraphDatabase.driver()

Return type:

Auth

neo4j.kerberos_auth(base64_encoded_ticket)

Generate a kerberos auth token with the base64 encoded ticket.

This will set the scheme to “kerberos” for the auth token.

Parameters:

base64_encoded_ticket (str) – a base64 encoded service ticket, this will set the credentials

Returns:

auth token for use with GraphDatabase.driver() or AsyncGraphDatabase.driver()

Return type:

Auth

neo4j.bearer_auth(base64_encoded_token)

Generate an auth token for Single-Sign-On providers.

This will set the scheme to “bearer” for the auth token.

Parameters:

base64_encoded_token (str) – a base64 encoded authentication token generated by a Single-Sign-On provider.

Returns:

auth token for use with GraphDatabase.driver() or AsyncGraphDatabase.driver()

Return type:

Auth

neo4j.custom_auth(principal, credentials, realm, scheme, **parameters)

Generate a custom auth token.

Parameters:
  • principal (str | None) – specifies who is being authenticated

  • credentials (str | None) – authenticates the principal

  • realm (str | None) – specifies the authentication provider

  • scheme (str | None) – specifies the type of authentication

  • parameters (Any) – extra key word parameters passed along to the authentication provider

Returns:

auth token for use with GraphDatabase.driver() or AsyncGraphDatabase.driver()

Return type:

Auth

Driver

Every Neo4j-backed application will require a driver object.

This object holds the details required to establish connections with a Neo4j database, including server URIs, credentials and other configuration. neo4j.Driver objects hold a connection pool from which neo4j.Session objects can borrow connections. Closing a driver will immediately shut down all connections in the pool.

Note

Driver objects only open connections and pool them as needed. To verify that the driver is able to communicate with the database without executing any query, use neo4j.Driver.verify_connectivity().

class neo4j.Driver

Base class for all driver types.

Drivers are used as the primary access point to Neo4j.

execute_query(query, parameters_=None, routing_=neo4j.RoutingControl.WRITE, database_=None, impersonated_user_=None, bookmark_manager_=self.execute_query_bookmark_manager, auth_=None, result_transformer_=Result.to_eager_result, **kwargs)

Execute a query in a transaction function and return all results.

This method is a handy wrapper for lower-level driver APIs like sessions, transactions, and transaction functions. It is intended for simple use cases where there is no need for managing all possible options.

The internal usage of transaction functions provides a retry-mechanism for appropriate errors. Furthermore, this means that queries using CALL {} IN TRANSACTIONS or the older USING PERIODIC COMMIT will not work (use Session.run() for these).

The method is roughly equivalent to:

def execute_query(
    query_, parameters_, routing_, database_, impersonated_user_,
    bookmark_manager_, auth_, result_transformer_, **kwargs
):
    @unit_of_work(query_.metadata, query_.timeout)
    def work(tx):
        result = tx.run(query_.text, parameters_, **kwargs)
        return result_transformer_(result)

    with driver.session(
        database=database_,
        impersonated_user=impersonated_user_,
        bookmark_manager=bookmark_manager_,
        auth=auth_,
    ) as session:
        if routing_ == RoutingControl.WRITE:
            return session.execute_write(work)
        elif routing_ == RoutingControl.READ:
            return session.execute_read(work)

Usage example:

from typing import List

import neo4j


def example(driver: neo4j.Driver) -> List[str]:
    """Get the name of all 42 year-olds."""
    records, summary, keys = driver.execute_query(
        "MATCH (p:Person {age: $age}) RETURN p.name",
        {"age": 42},
        routing_=neo4j.RoutingControl.READ,  # or just "r"
        database_="neo4j",
    )
    assert keys == ["p.name"]  # not needed, just for illustration
    # log_summary(summary)  # log some metadata
    return [str(record["p.name"]) for record in records]
    # or: return [str(record[0]) for record in records]
    # or even: return list(map(lambda r: str(r[0]), records))

Another example: