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.

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 a 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

driver = neo4j.GraphDatabase.driver(...)
bookmark_manager = neo4j.GraphDatabase.bookmark_manager(...)

with driver.session(
    bookmark_manager=bookmark_manager
) as session1:
    with driver.session(
        bookmark_manager=bookmark_manager,
        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 (Optional[Mapping[str, Union[neo4j.api.Bookmarks, Iterable[str]]]]) – The initial set of bookmarks. The returned bookmark manager will use this to initialize its internal bookmarks per database. If present, this parameter must be a mapping of database names to Bookmarks or an iterable of raw bookmark values (str).

  • bookmarks_supplier (Optional[Callable[[Optional[str]], neo4j.api.Bookmarks]]) – Function which will be called every time the default bookmark manager’s method BookmarkManager.get_bookmarks() or BookmarkManager.get_all_bookmarks() gets called. The function will be passed the name of the database (str) if .get_bookmarks is called or None if .get_all_bookmarks is called. The function 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.

  • bookmarks_consumer (Optional[Callable[[str, neo4j.api.Bookmarks], 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 name of the database and the new set of bookmarks.

Returns

A default implementation of BookmarkManager.

Return type

neo4j.api.BookmarkManager

This is experimental. (See Filter Warnings) It might be changed or removed any time even without prior notice.

New in version 5.0.

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"

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.

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.

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.

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 the details.

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

Container for auth details.

Parameters
  • scheme (t.Optional[str]) – specifies the type of authentication, examples: “basic”, “kerberos”

  • principal (t.Optional[str]) – specifies who is being authenticated

  • credentials (t.Optional[str]) – authenticates the principal

  • realm (t.Optional[str]) – specifies the authentication provider

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

Return type

None

Example:

import neo4j

auth = neo4j.Auth("basic", "neo4j", "password")

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

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

  • realm (Optional[str]) – specifies the authentication provider

Returns

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

Return type

neo4j.api.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

neo4j.api.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

neo4j.api.Auth

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

Generate a custom auth token.

Parameters
  • principal (Optional[str]) – specifies who is being authenticated

  • credentials (Optional[str]) – authenticates the principal

  • realm (Optional[str]) – specifies the authentication provider

  • scheme (Optional[str]) – 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

neo4j.api.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 types of neo4j.Driver, instances of which are used as the primary access point to Neo4j.

property encrypted: bool

Indicate whether the driver was configured to use encryption.

session(**config)

Create a session, see Session Construction

Parameters

config – session configuration key-word arguments, see Session Configuration for available key-word arguments.

Returns

new neo4j.Session object

Return type

neo4j._sync.work.session.Session

close()

Shut down, closing any open connections in the pool.

Return type

None

verify_connectivity(**config)

Verify that the driver can establish a connection to the server.

This verifies if the driver can establish a reading connection to a remote server or a cluster. Some data will be exchanged.

Note

Even if this method raises an exception, the driver still needs to be closed via close() to free up all resources.

Parameters

config

accepts the same configuration key-word arguments as session().

Warning

All configuration key-word arguments are experimental. They might be changed or removed in any future version without prior notice.

Raises

DriverError – if the driver cannot connect to the remote. Use the exception to further understand the cause of the connectivity problem.

Return type

None

Changed in version 5.0: The undocumented return value has been removed. If you need information about the remote server, use get_server_info() instead.

get_server_info(**config)

Get information about the connected Neo4j server.

Try to establish a working read connection to the remote server or a member of a cluster and exchange some data. Then return the contacted server’s information.

In a cluster, there is no guarantee about which server will be contacted.

Note

Even if this method raises an exception, the driver still needs to be closed via close() to free up all resources.

Parameters

config

accepts the same configuration key-word arguments as session().

Warning

All configuration key-word arguments are experimental. They might be changed or removed in any future version without prior notice.

Raises

DriverError – if the driver cannot connect to the remote. Use the exception to further understand the cause of the connectivity problem.

Return type

neo4j.api.ServerInfo

New in version 5.0.

Driver Configuration

Additional configuration can be provided via the neo4j.Driver constructor.

connection_acquisition_timeout

The maximum amount of time in seconds the driver will wait to either acquire an idle connection from the pool (including potential liveness checks) or create a new connection when the pool is not full and all existing connection are in use.

Since this process may involve opening a new connection including handshakes, it should be chosen larger than connection_timeout.

Type

float

Default

60.0

connection_timeout

The maximum amount of time in seconds to wait for a TCP connection to be established.

This does not include any handshake(s), or authentication required before the connection can be used to perform database related work.

Type

float

Default

30.0

encrypted

Specify whether to use an encrypted connection between the driver and server.

This setting does not have any effect if a custom ssl_context is configured.

Type

bool

Default

False

keep_alive

Specify whether TCP keep-alive should be enabled.

Type

bool

Default

True

This is experimental. (See Filter Warnings) It might be changed or removed any time even without prior notice.

max_connection_lifetime

The maximum duration in seconds that the driver will keep a connection for before being removed from the pool.

Type

float

Default

3600

max_connection_pool_size

The maximum total number of connections allowed, per host (i.e. cluster nodes), to be managed by the connection pool.

Type

int

Default

100

max_transaction_retry_time

The maximum amount of time in seconds that a managed transaction will retry before failing.

Type

float

Default

30.0

resolver

A custom resolver function to resolve host and port values ahead of DNS resolution. This function is called with a 2-tuple of (host, port) and should return an iterable of 2-tuples (host, port).

If no custom resolver function is supplied, the internal resolver moves straight to regular DNS resolution.

For example:

from neo4j import GraphDatabase

def custom_resolver(socket_address):
    if socket_address == ("example.com", 9999):
        yield "::1", 7687
        yield "127.0.0.1", 7687
    else:
        from socket import gaierror
        raise gaierror("Unexpected socket address %r" % socket_address)

driver = GraphDatabase.driver("neo4j://example.com:9999",
                              auth=("neo4j", "password"),
                              resolver=custom_resolver)
Default

None

trust

Specify how to determine the authenticity of encryption certificates provided by the Neo4j instance on connection.

This setting does not have any effect if encrypted is set to False.

Type

neo4j.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES, neo4j.TRUST_ALL_CERTIFICATES

neo4j.TRUST_ALL_CERTIFICATES

Trust any server certificate (default). This ensures that communication is encrypted but does not verify the server certificate against a certificate authority. This option is primarily intended for use with the default auto-generated server certificate.

neo4j.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES

Trust server certificates that can be verified against the system certificate authority. This option is primarily intended for use with full certificates.

Default

neo4j.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES.

Deprecated since version 5.0: This configuration option is deprecated and will be removed in a future release. Please use trusted_certificates instead.

ssl_context

Specify a custom SSL context to use for wrapping connections.

If given, encrypted and trusted_certificates have no effect.

Warning

This option may compromise your application’s security if used improperly.

Its usage is strongly discouraged and comes without any guarantees.

Type

ssl.SSLContext or None

Default

None

New in version 5.0.

trusted_certificates

Specify how to determine the authenticity of encryption certificates provided by the Neo4j instance on connection.

This setting does not have any effect if encrypted is set to False or a custom ssl_context is configured.

Type

TrustSystemCAs, TrustAll, or TrustCustomCAs

Default

neo4j.TrustSystemCAs()

class neo4j.TrustSystemCAs

Used to configure the driver to trust system CAs (default).

Trust server certificates that can be verified against the system certificate authority. This option is primarily intended for use with full certificates.

For example:

import neo4j

driver = neo4j.GraphDatabase.driver(
    url, auth=auth, trusted_certificates=neo4j.TrustSystemCAs()
)
class neo4j.TrustAll

Used to configure the driver to trust all certificates.

Trust any server certificate. This ensures that communication is encrypted but does not verify the server certificate against a certificate authority. This option is primarily intended for use with the default auto-generated server certificate.

For example:

import neo4j

driver = neo4j.GraphDatabase.driver(
    url, auth=auth, trusted_certificates=neo4j.TrustAll()
)
class neo4j.TrustCustomCAs(*certificates)

Used to configure the driver to trust custom CAs.

Trust server certificates that can be verified against the certificate authority at the specified paths. This option is primarily intended for self-signed and custom certificates.

Parameters

(str) (certificates) – paths to the certificates to trust. Those are not the certificates you expect to see from the server but the CA certificates you expect to be used to sign the server’s certificate.

For example:

import neo4j

driver = neo4j.GraphDatabase.driver(
    url, auth=auth,
    trusted_certificates=neo4j.TrustCustomCAs(
        "/path/to/ca1.crt", "/path/to/ca2.crt",
    )
)

New in version 5.0.

user_agent

Specify the client agent name.

Type

str

Default

The Python Driver will generate a user agent name.

Driver Object Lifetime

For general applications, it is recommended to create one top-level neo4j.Driver object that lives for the lifetime of the application.

For example:

from neo4j import GraphDatabase

class Application:

    def __init__(self, uri, user, password)
        self.driver = GraphDatabase.driver(uri, auth=(user, password))

    def close(self):
        self.driver.close()

Connection details held by the neo4j.Driver are immutable. Therefore if, for example, a password is changed, a replacement neo4j.Driver object must be created. More than one Driver may be required if connections to multiple databases, or connections as multiple users, are required, unless when using impersonation (impersonated_user).

neo4j.Driver objects are thread-safe but cannot be shared across processes. Therefore, multithreading should generally be preferred over multiprocessing for parallel database access. If using multiprocessing however, each process will require its own neo4j.Driver object.

BoltDriver

URI schemes:

bolt, bolt+ssc, bolt+s

Will result in:

class neo4j.BoltDriver(pool, default_workspace_config)

BoltDriver is instantiated for bolt URIs and addresses a single database machine. This may be a standalone server or could be a specific member of a cluster.

Connections established by a BoltDriver are always made to the exact host and port detailed in the URI.

This class is not supposed to be instantiated externally. Use GraphDatabase.driver() instead.

Neo4jDriver

URI schemes:

neo4j, neo4j+ssc, neo4j+s

Will result in:

class neo4j.Neo4jDriver(pool, default_workspace_config)

Neo4jDriver is instantiated for neo4j URIs. The routing behaviour works in tandem with Neo4j’s Causal Clustering feature by directing read and write behaviour to appropriate cluster members.

This class is not supposed to be instantiated externally. Use GraphDatabase.driver() instead.

Sessions & Transactions

All database activity is co-ordinated through two mechanisms: sessions (neo4j.Session) and transactions (neo4j.Transaction, neo4j.ManagedTransaction).

A session is a logical container for any number of causally-related transactional units of work. Sessions automatically provide guarantees of causal consistency within a clustered environment but multiple sessions can also be causally chained if required. Sessions provide the top level of containment for database activity. Session creation is a lightweight operation and sessions are not thread safe.

Connections are drawn from the neo4j.Driver connection pool as required.

A transaction is a unit of work that is either committed in its entirety or is rolled back on failure.

Session Construction

To construct a neo4j.Session use the neo4j.Driver.session() method.

from neo4j import GraphDatabase

driver = GraphDatabase(uri, auth=(user, password))
session = driver.session()
result = session.run("MATCH (a:Person) RETURN a.name AS name")
names = [record["name"] for record in result]
session.close()
driver.close()

Sessions will often be created and destroyed using a with block context. This is the recommended approach as it takes care of closing the session properly even when an exception is raised.

with driver.session() as session:
    result = session.run("MATCH (a:Person) RETURN a.name AS name")
    # do something with the result...

Sessions will often be created with some configuration settings, see Session Configuration.

with driver.session(database="example_database", fetch_size=100) as session:
    result = session.run("MATCH (a:Person) RETURN a.name AS name")
    # do something with the result...

Session

class neo4j.Session

A Session is a logical context for transactional units of work. Connections are drawn from the Driver connection pool as required.

Session creation is a lightweight operation and sessions are not safe to be used in concurrent contexts (multiple threads/coroutines). Therefore, a session should generally be short-lived, and must not span multiple threads/asynchronous Tasks.

In general, sessions will be created and destroyed within a with context. For example:

with driver.session() as session:
    result = session.run("MATCH (n:Person) RETURN n.name AS name")
    # do something with the result...
Parameters
  • pool – connection pool instance

  • config – session config instance

close()

Close the session.

This will release any borrowed resources, such as connections, and will roll back any outstanding transactions.

Return type

None

closed()

Indicate whether the session has been closed.

Returns

True if closed, False otherwise.

Return type

bool

run(query, parameters=None, **kwargs)

Run a Cypher query within an auto-commit transaction.

The query is sent and the result header received immediately but the neo4j.Result content is fetched lazily as consumed by the client application.

If a query is executed before a previous neo4j.Result in the same Session has been fully consumed, the first result will be fully fetched and buffered. Note therefore that the generally recommended pattern of usage is to fully consume one result before executing a subsequent query. If two results need to be consumed in parallel, multiple Session objects can be used as an alternative to result buffering.

For more usage details, see Transaction.run().

Parameters
Raises

SessionError – if the session has been closed.

Returns

a new neo4j.Result object

Return type

neo4j._sync.work.result.Result

last_bookmarks()

Return most recent bookmarks of the session.

Bookmarks can be used to causally chain sessions. For example, if a session (session1) wrote something, that another session (session2) needs to read, use session2 = driver.session(bookmarks=session1.last_bookmarks()) to achieve this.

Combine the bookmarks of multiple sessions like so:

bookmarks1 = session1.last_bookmarks()
bookmarks2 = session2.last_bookmarks()
session3 = driver.session(bookmarks=bookmarks1 + bookmarks2)

A session automatically manages bookmarks, so this method is rarely needed. If you need causal consistency, try to run the relevant queries in the same session.

“Most recent bookmarks” are either the bookmarks passed to the session or creation, or the last bookmark the session received after committing a transaction to the server.

Note: For auto-transactions (Session.run()), this will trigger Result.consume() for the current result.

Returns

the session’s last known bookmarks

Return type

neo4j.api.Bookmarks

last_bookmark()

Return the bookmark received following the last completed transaction.

Note: For auto-transactions (Session.run()), this will trigger Result.consume() for the current result.

Warning

This method can lead to unexpected behaviour if the session has not yet successfully completed a transaction.

Deprecated since version 5.0: last_bookmark() will be removed in version 6.0. Use last_bookmarks() instead.

Returns

last bookmark

Return type

Optional[str]

begin_transaction(metadata=None, timeout=None)
Begin a new unmanaged transaction. Creates a new Transaction within this session.

At most one transaction may exist in a session at any point in time. To maintain multiple concurrent transactions, use multiple concurrent sessions.

Note: For auto-transaction (Session.run) this will trigger a consume for the current result.

Parameters
Raises
Returns

A new transaction instance.

Return type

neo4j._sync.work.transaction.Transaction

read_transaction(transaction_function, *args, **kwargs)

Execute a unit of work in a managed read transaction.

Note

This does not necessarily imply access control, see the session configuration option default_access_mode.

This transaction will automatically be committed when the function returns, unless an exception is thrown during query execution or by the user code. Note, that this function performs retries and that the supplied transaction_function might get invoked more than once. Therefore, it needs to be idempotent (i.e., have the same effect, regardless if called once or many times).

Example:

def do_cypher_tx(tx, cypher):
    result = tx.run(cypher)
    values = [record.values() for record in result]
    return values

with driver.session() as session:
    values = session.read_transaction(do_cypher_tx, "RETURN 1 AS x")

Example:

def get_two_tx(tx):
    result = tx.run("UNWIND [1,2,3,4] AS x RETURN x")
    values = []
    for record in result:
        if len(values) >= 2:
            break
        values.append(record.values())
    # or shorter: values = [record.values()
    #                       for record in result.fetch(2)]

    # discard the remaining records if there are any
    summary = result.consume()
    # use the summary for logging etc.
    return values

with driver.session() as session:
    values = session.read_transaction(get_two_tx)
Parameters
  • transaction_function (t.Callable[te.Concatenate[ManagedTransaction, _P], t.Union[_R]]) – a function that takes a transaction as an argument and does work with the transaction. transaction_function(tx, *args, **kwargs) where tx is a ManagedTransaction.

  • args (_P.args) – additional arguments for the transaction_function

  • kwargs (_P.kwargs) – key word arguments for the transaction_function

Raises

SessionError – if the session has been closed.

Returns

a result as returned by the given unit of work

Return type

_R

Deprecated since version 5.0: Method was renamed to execute_read().

execute_read(transaction_function, *args, **kwargs)

Execute a unit of work in a managed read transaction.

Note

This does not necessarily imply access control, see the session configuration option default_access_mode.

This transaction will automatically be committed when the function returns, unless an exception is thrown during query execution or by the user code. Note, that this function performs retries and that the supplied transaction_function might get invoked more than once. Therefore, it needs to be idempotent (i.e., have the same effect, regardless if called once or many times).

Example:

def do_cypher_tx(tx, cypher):
    result = tx.run(cypher)
    values = [record.values() for record in result]
    return values

with driver.session() as session:
    values = session.execute_read(do_cypher_tx, "RETURN 1 AS x")

Example:

def get_two_tx(tx):
    result = tx.run("UNWIND [1,2,3,4] AS x RETURN x")
    values = []
    for record in result:
        if len(values) >= 2:
            break
        values.append(record.values())
    # or shorter: values = [record.values()
    #                       for record in result.fetch(2)]

    # discard the remaining records if there are any
    summary = result.consume()
    # use the summary for logging etc.
    return values

with driver.session() as session:
    values = session.execute_read(get_two_tx)
Parameters
  • transaction_function (t.Callable[te.Concatenate[ManagedTransaction, _P], t.Union[_R]]) – a function that takes a transaction as an argument and does work with the transaction. transaction_function(tx, *args, **kwargs) where tx is a ManagedTransaction.

  • args (_P.args) – additional arguments for the transaction_function

  • kwargs (_P.kwargs) – key word arguments for the transaction_function

Raises

SessionError – if the session has been closed.

Returns

a result as returned by the given unit of work

Return type

_R

New in version 5.0.

write_transaction(transaction_function, *args, **kwargs)

Execute a unit of work in a managed write transaction.

Note

This does not necessarily imply access control, see the session configuration option default_access_mode.

This transaction will automatically be committed when the function returns unless, an exception is thrown during query execution or by the user code. Note, that this function performs retries and that the supplied transaction_function might get invoked more than once. Therefore, it needs to be idempotent (i.e., have the same effect, regardless if called once or many times).

Example:

def create_node_tx(tx, name):
    query = "CREATE (n:NodeExample { name: $name }) RETURN id(n) AS node_id"
    result = tx.run(query, name=name)
    record = result.single()
    return record["node_id"]

with driver.session() as session:
    node_id = session.write_transaction(create_node_tx, "example")
Parameters
  • transaction_function (t.Callable[te.Concatenate[ManagedTransaction, _P], t.Union[_R]]) – a function that takes a transaction as an argument and does work with the transaction. transaction_function(tx, *args, **kwargs) where tx is a ManagedTransaction.

  • args (_P.args) – additional arguments for the transaction_function

  • kwargs (_P.kwargs) – key word arguments for the transaction_function

Raises

SessionError – if the session has been closed.

Returns

a result as returned by the given unit of work

Return type

_R

Deprecated since version 5.0: Method was renamed to execute_write().

execute_write(transaction_function, *args, **kwargs)

Execute a unit of work in a managed write transaction.

Note

This does not necessarily imply access control, see the session configuration option default_access_mode.

This transaction will automatically be committed when the function returns unless, an exception is thrown during query execution or by the user code. Note, that this function performs retries and that the supplied transaction_function might get invoked more than once. Therefore, it needs to be idempotent (i.e., have the same effect, regardless if called once or many times).

Example:

def create_node_tx(tx, name):
    query = "CREATE (n:NodeExample { name: $name }) RETURN id(n) AS node_id"
    result = tx.run(query, name=name)
    record = result.single()
    return record["node_id"]

with driver.session() as session:
    node_id = session.execute_write(create_node_tx, "example")
Parameters
  • transaction_function (t.Callable[te.Concatenate[ManagedTransaction, _P], t.Union[_R]]) – a function that takes a transaction as an argument and does work with the transaction. transaction_function(tx, *args, **kwargs) where tx is a ManagedTransaction.

  • args (_P.args) – additional arguments for the transaction_function

  • kwargs (_P.kwargs) – key word arguments for the transaction_function

Raises

SessionError – if the session has been closed.

Returns

a result as returned by the given unit of work

Return type

_R

New in version 5.0.

Query

class neo4j.Query(text, metadata=None, timeout=None)

Create a new query.

Parameters
  • text (str) – The query text.

  • metadata (t.Optional[t.Dict[str, t.Any]]) – metadata attached to the query.

  • timeout (t.Optional[float]) – seconds.

Return type

None

Session Configuration

To construct a neo4j.Session use the neo4j.Driver.session() method. This section describes the session configuration key-word arguments.

bookmarks

Optional neo4j.Bookmarks. Use this to causally chain sessions. See Session.last_bookmarks() or AsyncSession.last_bookmarks() for more information.

Deprecated since version 5.0: Alternatively, an iterable of strings can be passed. This usage is deprecated and will be removed in a future release. Please use a neo4j.Bookmarks object instead.

Default

None

database

Name of the database to query.

Type

str, neo4j.DEFAULT_DATABASE

neo4j.DEFAULT_DATABASE

This will use the default database on the Neo4j instance.

Note

The default database can be set on the Neo4j instance settings.

Note

It is recommended to always specify the database explicitly when possible. This allows the driver to work more efficiently, as it will not have to resolve the home database first.

from neo4j import GraphDatabase

driver = GraphDatabase.driver(uri, auth=(user, password))
session = driver.session(database="system")
Default

neo4j.DEFAULT_DATABASE

impersonated_user

Name of the user to impersonate. This means that all actions in the session will be executed in the security context of the impersonated user. For this, the user for which the Driver has been created needs to have the appropriate permissions.

Type

str, None

None

Will not perform impersonation.

Note

The server or all servers of the cluster need to support impersonation. Otherwise, the driver will raise ConfigurationError as soon as it encounters a server that does not.

from neo4j import GraphDatabase

driver = GraphDatabase.driver(uri, auth=(user, password))
session = driver.session(impersonated_user="alice")
Default

None

default_access_mode

The default access mode.

A session can be given a default access mode on construction.

This applies only in clustered environments and determines whether transactions carried out within that session should be routed to a read or write server by default.

Transactions (see Managed Transactions (transaction functions)) within a session override the access mode passed to that session on construction.

Note

The driver does not parse Cypher queries and cannot determine whether the access mode should be neo4j.WRITE_ACCESS or neo4j.READ_ACCESS. This setting is only meant to enable the driver to perform correct routing, not for enforcing access control. This means that, depending on the server version and settings, the server or cluster might allow a write-statement to be executed even when neo4j.READ_ACCESS is chosen. This behaviour should not be relied upon as it can change with the server.

Type

neo4j.WRITE_ACCESS, neo4j.READ_ACCESS

Default

neo4j.WRITE_ACCESS

fetch_size

The fetch size used for requesting messages from Neo4j.

Type

int

Default

1000

bookmark_manager

Specify a bookmark manager for the session to use. If present, the bookmark manager is used to keep all work within the session causally consistent with all work in other sessions using the same bookmark manager.

See BookmarkManager for more information.

Warning

Enabling the BookmarkManager can have a negative impact on performance since all queries will wait for the latest changes to be propagated across the cluster.

For simple use-cases, it often suffices that work within a single session is automatically causally consistent.

Type

None or BookmarkManager

Default

None

New in version 5.0.

This is experimental. (See Filter Warnings) It might be changed or removed any time even without prior notice.

Transaction

Neo4j supports three kinds of transaction:

Each has pros and cons but if in doubt, use a managed transaction with a transaction function.

Auto-commit Transactions

Auto-commit transactions are the simplest form of transaction, available via neo4j.Session.run(). These are easy to use but support only one statement per transaction and are not automatically retried on failure.

Auto-commit transactions are also the only way to run PERIODIC COMMIT (only Neo4j 4.4 and earlier) or CALL {...} IN TRANSACTIONS (Neo4j 4.4 and newer) statements, since those Cypher clauses manage their own transactions internally.

Example:

import neo4j

def create_person(driver, name):
    with driver.session(default_access_mode=neo4j.WRITE_ACCESS) as session:
        query = "CREATE (a:Person { name: $name }) RETURN id(a) AS node_id"
        result = session.run(query, name=name)
        record = result.single()
        return record["node_id"]

Example:

import neo4j

def get_numbers(driver):
    numbers = []
    with driver.session(default_access_mode=neo4j.READ_ACCESS) as session:
        result = session.run("UNWIND [1, 2, 3] AS x RETURN x")
        for record in result:
            numbers.append(record["x"])
    return numbers

Explicit Transactions

Explicit transactions support multiple statements and must be created with an explicit neo4j.Session.begin_transaction() call.

This creates a new neo4j.Transaction object that can be used to run Cypher.

It also gives applications the ability to directly control commit and rollback activity.

class neo4j.Transaction

Container for multiple Cypher queries to be executed within a single context. Transaction objects can be used as a context managers (with block) where the transaction is committed or rolled back on based on whether an exception is raised:

with session.begin_transaction() as tx:
    ...
run(query, parameters=None, **kwparameters)

Run a Cypher query within the context of this transaction.

Cypher is typically expressed as a query template plus a set of named parameters. In Python, parameters may be expressed through a dictionary of parameters, through individual parameter arguments, or as a mixture of both. For example, the run queries below are all equivalent:

>>> query = "CREATE (a:Person { name: $name, age: $age })"
>>> result = tx.run(query, {"name": "Alice", "age": 33})
>>> result = tx.run(query, {"name": "Alice"}, age=33)
>>> result = tx.run(query, name="Alice", age=33)

Parameter values can be of any type supported by the Neo4j type system. In Python, this includes bool, int, str, list and dict. Note however that list properties must be homogenous.

Parameters
  • query (str) – cypher query

  • parameters (Optional[Dict[str, Any]]) – dictionary of parameters

  • kwparameters (Any) – additional keyword parameters. These take precedence over parameters passed as parameters.

Raises

TransactionError – if the transaction is already closed

Returns

a new neo4j.Result object

Return type

neo4j._sync.work.result.Result

commit()

Mark this transaction as successful and close in order to trigger a COMMIT.

Raises

TransactionError – if the transaction is already closed

rollback()

Mark this transaction as unsuccessful and close in order to trigger a ROLLBACK.

Raises

TransactionError – if the transaction is already closed

close()

Close this transaction, triggering a ROLLBACK if not closed.

closed()

Indicate whether the transaction has been closed or cancelled.

Returns

True if closed or cancelled, False otherwise.

Return type

bool

Closing an explicit transaction can either happen automatically at the end of a with block, or can be explicitly controlled through the neo4j.Transaction.commit(), neo4j.Transaction.rollback() or neo4j.Transaction.close() methods.

Explicit transactions are most useful for applications that need to distribute Cypher execution across multiple functions for the same transaction.

Example:

import neo4j

def create_person(driver, name):
    with driver.session(default_access_mode=neo4j.WRITE_ACCESS) as session:
        tx = session.begin_transaction()
        node_id = create_person_node(tx)
        set_person_name(tx, node_id, name)
        tx.commit()

def create_person_node(tx):
    query = "CREATE (a:Person { name: $name }) RETURN id(a) AS node_id"
    name = "default_name"
    result = tx.run(query, name=name)
    record = result.single()
    return record["node_id"]

def set_person_name(tx, node_id, name):
    query = "MATCH (a:Person) WHERE id(a) = $id SET a.name = $name"
    result = tx.run(query, id=node_id, name=name)
    summary = result.consume()
    # use the summary for logging etc.

Managed Transactions (transaction functions)

Transaction functions are the most powerful form of transaction, providing access mode override and retry capabilities.

These allow a function object representing the transactional unit of work to be passed as a parameter. This function is called one or more times, within a configurable time limit, until it succeeds. Results should be fully consumed within the function and only aggregate or status values should be returned. Returning a live result object would prevent the driver from correctly managing connections and would break retry guarantees.

This function will receive a neo4j.ManagedTransaction object as its first parameter.

class neo4j.ManagedTransaction

Transaction object provided to transaction functions.

Inside a transaction function, the driver is responsible for managing (committing / rolling back) the transaction. Therefore, ManagedTransactions don’t offer such methods. Otherwise, they behave like Transaction.

  • To commit the transaction, return anything from the transaction function.

  • To rollback the transaction, raise any exception.

Note that transaction functions have to be idempotent (i.e., the result of running the function once has to be the same as running it any number of times). This is, because the driver will retry the transaction function if the error is classified as retryable.

New in version 5.0: Prior, transaction functions used Transaction objects, but would cause hard to interpret errors when managed explicitly (committed or rolled back by user code).

run(query, parameters=None, **kwparameters)

Run a Cypher query within the context of this transaction.

Cypher is typically expressed as a query template plus a set of named parameters. In Python, parameters may be expressed through a dictionary of parameters, through individual parameter arguments, or as a mixture of both. For example, the run queries below are all equivalent:

>>> query = "CREATE (a:Person { name: $name, age: $age })"
>>> result = tx.run(query, {"name": "Alice", "age": 33})
>>> result = tx.run(query, {"name": "Alice"}, age=33)
>>> result = tx.run(query, name="Alice", age=33)

Parameter values can be of any type supported by the Neo4j type system. In Python, this includes bool, int, str, list and dict. Note however that list properties must be homogenous.

Parameters
  • query (str) – cypher query

  • parameters (Optional[Dict[str, Any]]) – dictionary of parameters

  • kwparameters (Any) – additional keyword parameters. These take precedence over parameters passed as parameters.

Raises

TransactionError – if the transaction is already closed

Returns

a new neo4j.Result object

Return type

neo4j._sync.work.result.Result

Example:

def create_person(driver, name)
    with driver.session() as session:
        node_id = session.execute_write(create_person_tx, name)

def create_person_tx(tx, name):
    query = "CREATE (a:Person { name: $name }) RETURN id(a) AS node_id"
    result = tx.run(query, name=name)
    record = result.single()
    return record["node_id"]

To exert more control over how a transaction function is carried out, the neo4j.unit_of_work() decorator can be used.

neo4j.unit_of_work(metadata=None, timeout=None)

Decorator giving extra control over transaction function configuration.

This function is a decorator for transaction functions that allows extra control over how the transaction is carried out.

For example, a timeout may be applied:

from neo4j import unit_of_work

@unit_of_work(timeout=100)
def count_people_tx(tx):
    result = tx.run("MATCH (a:Person) RETURN count(a) AS persons")
    record = result.single()
    return record["persons"]
Parameters
  • metadata (t.Optional[t.Dict[str, t.Any]]) – a dictionary with metadata. Specified metadata will be attached to the executing transaction and visible in the output of SHOW TRANSACTIONS YIELD * It will also get logged to the query.log. This functionality makes it easier to tag transactions and is equivalent to the dbms.setTXMetaData procedure, see https://neo4j.com/docs/cypher-manual/current/clauses/transaction-clauses/#query-listing-transactions and https://neo4j.com/docs/operations-manual/current/reference/procedures/ for reference.

  • timeout (t.Optional[float]) – the transaction timeout in seconds. Transactions that execute longer than the configured timeout will be terminated by the database. This functionality allows to limit query/transaction execution time. Specified timeout overrides the default timeout configured in the database using dbms.transaction.timeout setting. Values higher than dbms.transaction.timeout will be ignored and will fall back to default (unless using Neo4j < 4.2). Value should not represent a negative duration. A zero duration will make the transaction execute indefinitely. None will use the default timeout configured in the database.

Return type

t.Callable[[_T], _T]

Result

Every time a query is executed, a neo4j.Result is returned.

This provides a handle to the result of the query, giving access to the records within it as well as the result metadata.

Results also contain a buffer that automatically stores unconsumed records when results are consumed out of order.

A neo4j.Result is attached to an active connection, through a neo4j.Session, until all its content has been buffered or consumed.

class neo4j.Result

A handler for the result of Cypher query execution. Instances of this class are typically constructed and returned by AyncSession.run() and Transaction.run().

iter(result)
next(result)
keys()

The keys for the records in this result.

Returns

tuple of key names

Return type

tuple

consume()

Consume the remainder of this result and return a neo4j.ResultSummary.

Example:

def create_node_tx(tx, name):
    result = tx.run(
        "CREATE (n:ExampleNode { name: $name }) RETURN n", name=name
    )
    record = result.single()
    value = record.value()
    summary = result.consume()
    return value, summary

with driver.session() as session:
    node_id, summary = session.execute_write(
        create_node_tx, "example"
    )

Example:

def get_two_tx(tx):
    result = tx.run("UNWIND [1,2,3,4] AS x RETURN x")
    values = []
    for record in result:
        if len(values) >= 2:
            break
        values.append(record.values())
    # or shorter: values = [record.values()
    #                       for record in result.fetch(2)]

    # discard the remaining records if there are any
    summary = result.consume()
    # use the summary for logging etc.
    return values, summary

with driver.session() as session:
    values, summary = session.execute_read(get_two_tx)
Returns

The neo4j.ResultSummary for this result

Raises

ResultConsumedError – if the transaction from which this result was obtained has been closed.

Return type

neo4j.work.summary.ResultSummary

Changed in version 5.0: Can raise ResultConsumedError.

single(strict: te.Literal[False] = False) Optional[neo4j._data.Record]
single(strict: te.Literal[True]) neo4j._data.Record

Obtain the next and only remaining record or None.

Calling this method always exhausts the result.

A warning is generated if more than one record is available but the first of these is still returned.

Parameters

strict – If True, raise a neo4j.ResultNotSingleError instead of returning None if there is more than one record or warning if there are more than 1 record. False by default.

Warns

if more than one record is available

Raises
  • ResultNotSingleError – If strict=True and not exactly one record is available.

  • ResultConsumedError – if the transaction from which this result was obtained has been closed or the Result has been explicitly consumed.

Returns

the next neo4j.Record or None if none remain

Changed in version 5.0: Added strict parameter.

Changed in version 5.0: Can raise ResultConsumedError.

fetch(n)

Obtain up to n records from this result.

Parameters

n (int) – the maximum number of records to fetch.

Returns

list of neo4j.Record

Raises

ResultConsumedError – if the transaction from which this result was obtained has been closed or the Result has been explicitly consumed.

Return type

List[neo4j._data.Record]

New in version 5.0.

peek()

Obtain the next record from this result without consuming it. This leaves the record in the buffer for further processing.

Returns

the next neo4j.Record or None if none remain.

Raises

ResultConsumedError – if the transaction from which this result was obtained has been closed or the Result has been explicitly consumed.

Return type

Optional[neo4j._data.Record]

Changed in version 5.0: Can raise ResultConsumedError.

graph()

Return a neo4j.graph.Graph instance containing all the graph objects in the result. After calling this method, the result becomes detached, buffering all remaining records.

Raises

ResultConsumedError – if the transaction from which this result was obtained has been closed or the Result has been explicitly consumed.

Returns

a result graph

Return type

Graph

Changed in version 5.0: Can raise ResultConsumedError.

value(key=0, default=None)

Helper function that return the remainder of the result as a list of values.

See neo4j.Record.value

Parameters
  • key (Union[int, str]) – field to return for each remaining record. Obtain a single value from the record by index or key.

  • default (Optional[object]) – default value, used if the index of key is unavailable

Raises

ResultConsumedError – if the transaction from which this result was obtained has been closed or the Result has been explicitly consumed.

Returns

list of individual values

Return type

List[Any]

Changed in version 5.0: Can raise ResultConsumedError.

values(*keys)

Helper function that return the remainder of the result as a list of values lists.

See neo4j.Record.values

Parameters

keys (Union[int, str]) – fields to return for each remaining record. Optionally filtering to include only certain values by index or key.

Raises

ResultConsumedError – if the transaction from which this result was obtained has been closed or the Result has been explicitly consumed.

Returns

list of values lists

Return type

List[List[Any]]

Changed in version 5.0: Can raise ResultConsumedError.

data(*keys)

Helper function that return the remainder of the result as a list of dictionaries.

See neo4j.Record.data

Parameters

keys (Union[int, str]) – fields to return for each remaining record. Optionally filtering to include only certain values by index or key.

Returns

list of dictionaries

Return type

list

Raises

ResultConsumedError – if the transaction from which this result was obtained has been closed or the Result has been explicitly consumed.

Changed in version 5.0: Can raise ResultConsumedError.

to_df(expand=False, parse_dates=False)

Convert (the rest of) the result to a pandas DataFrame.

This method is only available if the pandas library is installed.

res = tx.run("UNWIND range(1, 10) AS n RETURN n, n+1 as m")
df = res.to_df()

for instance will return a DataFrame with two columns: n and m and 10 rows.

Parameters
  • expand (bool) –

    If True, some structures in the result will be recursively expanded (flattened out into multiple columns) like so (everything inside <...> is a placeholder):

    • Node objects under any variable <n> will be expanded into columns (the recursion stops here)

      • <n>().prop.<property_name> (any) for each property of the node.

      • <n>().element_id (str) the node’s element id. See Node.element_id.

      • <n>().labels (frozenset of str) the node’s labels. See Node.labels.

    • Relationship objects under any variable <r> will be expanded into columns (the recursion stops here)

      • <r>->.prop.<property_name> (any) for each property of the relationship.

      • <r>->.element_id (str) the relationship’s element id. See Relationship.element_id.

      • <r>->.start.element_id (str) the relationship’s start node’s element id. See Relationship.start_node.

      • <r>->.end.element_id (str) the relationship’s end node’s element id. See Relationship.end_node.

      • <r>->.type (str) the relationship’s type. See Relationship.type.

    • list objects under any variable <l> will be expanded into

      • <l>[].0 (any) the 1st list element

      • <l>[].1 (any) the 2nd list element

    • dict objects under any variable <d> will be expanded into

      • <d>{}.<key1> (any) the 1st key of the dict

      • <d>{}.<key2> (any) the 2nd key of the dict

    • list and dict objects are expanded recursively. Example:

      variable x: [{"foo": "bar", "baz": [42, 0]}, "foobar"]
      

      will be expanded to:

      {
          "x[].0{}.foo": "bar",
          "x[].0{}.baz[].0": 42,
          "n[].0{}.baz[].1": 0,
          "n[].1": "foobar"
      }
      
    • Everything else (including Path objects) will not be flattened.

    dict keys and variable names that contain . or \ will be escaped with a backslash (\. and \\ respectively).

  • parse_dates (bool) – If True, columns that exclusively contain time.DateTime objects, time.Date objects, or None, will be converted to pandas.Timestamp.

Raises
  • ImportError – if pandas library is not available.

  • ResultConsumedError – if the transaction from which this result was obtained has been closed or the Result has been explicitly consumed.

Return type

pandas.DataFrame

closed()

Return True if the result has been closed.

When a result gets consumed consume() or the transaction that owns the result gets closed (committed, rolled back, closed), the result cannot be used to acquire further records.

In such case, all methods that need to access the Result’s records, will raise a ResultConsumedError when called.

Returns

whether the result is closed.

Return type

bool

New in version 5.0.

See https://neo4j.com/docs/python-manual/current/cypher-workflow/#python-driver-type-mapping for more about type mapping.

Graph

class neo4j.graph.Graph

Local, self-contained graph object that acts as a container for Node and Relationship instances.

A local, self-contained graph object that acts as a container for Node and neo4j.Relationship instances. This is typically obtained via the neo4j.Result.graph() method.

Return type

None

nodes

Access a set view of the nodes in this graph.

relationships

Access a set view of the relationships in this graph.

relationship_type(name)

Obtain a Relationship subclass for a given relationship type name.

Parameters

name (str) –

Return type

Type[neo4j.graph.Relationship]

This is experimental. (See Filter Warnings) It might be changed or removed any time even without prior notice.

Record

class neo4j.Record

A Record is an immutable ordered collection of key-value pairs. It is generally closer to a namedtuple than to a OrderedDict in as much as iteration of the collection will yield values rather than keys.

Record(iterable)

Create a new record based on an dictionary-like iterable. This can be a dictionary itself, or may be a sequence of key-value pairs, each represented by a tuple.

record == other

Compare a record for equality with another value. The other value may be any Sequence or Mapping or both. If comparing with a Sequence the values are compared in order. If comparing with a Mapping the values are compared based on their keys. If comparing with a value that exhibits both traits, both comparisons must be true for the values to be considered equal.

record != other

Compare a record for inequality with another value. See above for comparison rules.

hash(record)

Create a hash for this record. This will raise a TypeError if any values within the record are unhashable.

record[index]

Obtain a value from the record by index. This will raise an IndexError if the specified index is out of range.

record[i:j]

Derive a sub-record based on a start and end index. All keys and values within those bounds will be copied across in the same order as in the original record.

keys()

Return the keys of the record.

Returns

list of key names

Return type

List[str]

record[key]

Obtain a value from the record by key. This will raise a KeyError if the specified key does not exist.

get(key, default=None)

Obtain a value from the record by key, returning a default value if the key does not exist.

Parameters
Returns

a value

Return type

Any

index(key)

Return the index of the given item.

Parameters

key (Union[int, str]) – a key

Returns

index

Return type

int

items(*keys)

Return the fields of the record as a list of key and value tuples

Returns

a list of value tuples

value(key=0, default=None)

Obtain a single value from the record by index or key. If no index or key is specified, the first value is returned. If the specified item does not exist, the default value is returned.

Parameters
Returns

a single value

Return type

Any

values(*keys)

Return the values of the record, optionally filtering to include only certain values by index or key.

Parameters

keys (Union[int, str]) – indexes or keys of the items to include; if none are provided, all values will be included

Returns

list of values

Return type

List[Any]

data(*keys)

Return the keys and values of this record as a dictionary, optionally including only certain values by index or key. Keys provided in the items that are not in the record will be inserted with a value of None; indexes provided that are out of bounds will trigger an IndexError.

Parameters

keys (Union[int, str]) – indexes or keys of the items to include; if none are provided, all values will be included

Raises

IndexError if an out-of-bounds index is specified

Returns

dictionary of values, keyed by field name

Return type

Dict[str, Any]

ResultSummary

class neo4j.ResultSummary

A summary of execution returned with a Result object.

Parameters
  • address (Address) –

  • metadata (t.Any) –

Return type

None

server: ServerInfo

A neo4j.ServerInfo instance. Provides some basic information of the server where the result is obtained from.

database: t.Optional[str]

The database name where this summary is obtained from.

query: t.Optional[str]

The query that was executed to produce this result.

parameters: t.Optional[t.Dict[str, t.Any]]

Dictionary of parameters passed with the statement.

query_type: t.Union[te.Literal['r', 'rw', 'w', 's'], None]
plan: t.Optional[dict]

Dictionary that describes how the database will execute the query.

profile: t.Optional[dict]

Dictionary that describes how the database executed the query.

notifications: t.Optional[t.List[dict]]

A list of Dictionaries containing notification information. Notifications provide extra information for a user executing a statement. They can be warnings about problematic queries or other valuable information that can be presented in a client. Unlike failures or errors, notifications do not affect the execution of a statement.

counters: SummaryCounters

A neo4j.SummaryCounters instance. Counters for operations the query triggered.

result_available_after: t.Optional[int]

The time it took for the server to have the result available. (milliseconds)

result_consumed_after: t.Optional[int]

The time it took for the server to consume the result. (milliseconds)

SummaryCounters

class neo4j.SummaryCounters

Contains counters for various operations that a query triggered.

Return type

None

nodes_created: int = 0
nodes_deleted: int = 0
relationships_created: int = 0
relationships_deleted: int = 0
properties_set: int = 0
labels_added: int = 0
labels_removed: int = 0
indexes_added: int = 0
indexes_removed: int = 0
constraints_added: int = 0
constraints_removed: int = 0
system_updates: int = 0
property contains_updates: bool

True if any of the counters except for system_updates, are greater than 0. Otherwise False.

property contains_system_updates: bool

True if the system database was updated, otherwise False.

ServerInfo

class neo4j.ServerInfo

Represents a package of information relating to a Neo4j server.

Parameters
  • address (Address) –

  • protocol_version (Version) –

property address: Address

Network address of the remote server.

property protocol_version: neo4j.api.Version

Bolt protocol version with which the remote server communicates. This is returned as a Version object, which itself extends a simple 2-tuple of (major, minor) integers.

property agent: str

Server agent string by which the remote server identifies itself.

property connection_id

Unique identifier for the remote server connection.

update(metadata)

Update server information with extra metadata. This is typically drawn from the metadata received after successful connection initialisation.

Parameters

metadata (dict) –

Return type

None

Core Data Types

Cypher supports a set of core data types that all map to built-in types in Python.

These include the common Boolean Integer Float and String types as well as List and Map that can hold heterogenous collections of any other type.

The core types with their general mappings are listed below:

Cypher Type

Python Type

Null

None

Boolean

bool

Integer

int

Float

float

String

str

Bytes [1]

bytearray

List

list

Map

dict

Note

  1. Bytes is not an actual Cypher type but is transparently passed through when used in parameters or query results.

In reality, the actual conversions and coercions that occur as values are passed through the system are more complex than just a simple mapping. The diagram below illustrates the actual mappings between the various layers, from driver to data store, for the core types.

_images/core_type_mappings.svg

Graph Data Types

Cypher queries can return entire graph structures as well as individual property values.

The graph data types detailed here model graph data returned from a Cypher query. Graph values cannot be passed in as parameters as it would be unclear whether the entity was intended to be passed by reference or by value. The identity or properties of that entity should be passed explicitly instead.

The driver contains a corresponding class for each of the graph types that can be returned.

Cypher Type

Python Type

Node

neo4j.graph.Node

Relationship

neo4j.graph.Relationship

Path

neo4j.graph.Path

Node

class neo4j.graph.Node(graph, element_id, id_, n_labels=None, properties=None)

Self-contained graph node.

Parameters
  • graph (Graph) –

  • element_id (str) –

  • id_ (int) –

  • n_labels (t.Optional[t.Iterable[str]]) –

  • properties (t.Optional[t.Dict[str, t.Any]]) –

Return type

None

node == other

Compares nodes for equality.

node != other

Compares nodes for inequality.

hash(node)

Computes the hash of a node.

len(node)

Returns the number of properties on a node.

iter(node)

Iterates through all properties on a node.

node[key]

Returns a node property by key. Raises KeyError if the key does not exist.

key in node

Checks whether a property key exists for a given node.

graph

The Graph to which this entity belongs.

id

The legacy identity of this entity in its container Graph.

Depending on the version of the server this entity was retrieved from, this may be empty (None).

Warning

This value can change for the same entity across multiple queries. Don’t rely on it for cross-query computations.

Deprecated since version 5.0: Use element_id instead.

element_id

The identity of this entity in its container Graph.

Warning

This value can change for the same entity across multiple queries. Don’t rely on it for cross-query computations.

New in version 5.0.

labels

The set of labels attached to this node.

get(name, default=None)

Get a property value by name, optionally with a default.

Parameters
Return type

Any

keys()

Return an iterable of all property names.

Return type

KeysView[str]

values()

Return an iterable of all property values.

Return type

ValuesView[Any]

items()

Return an iterable of all property name-value pairs.

Return type

ItemsView[str, Any]

Relationship

class neo4j.graph.Relationship(graph, element_id, id_, properties)

Self-contained graph relationship.

Parameters
  • graph (Graph) –

  • element_id (str) –

  • id_ (int) –

  • properties (t.Dict[str, t.Any]) –

Return type

None

relationship == other

Compares relationships for equality.

relationship != other

Compares relationships for inequality.

hash(relationship)

Computes the hash of a relationship.

len(relationship)

Returns the number of properties on a relationship.

iter(relationship)

Iterates through all properties on a relationship.

relationship[key]

Returns a relationship property by key. Raises KeyError if the key does not exist.

key in relationship

Checks whether a property key exists for a given relationship.

type(relationship)

Returns the type (class) of a relationship. Relationship objects belong to a custom subtype based on the type name in the underlying database.

graph

The Graph to which this entity belongs.

id

The legacy identity of this entity in its container Graph.

Depending on the version of the server this entity was retrieved from, this may be empty (None).

Warning

This value can change for the same entity across multiple queries. Don’t rely on it for cross-query computations.

Deprecated since version 5.0: Use element_id instead.

element_id

The identity of this entity in its container Graph.

Warning

This value can change for the same entity across multiple queries. Don’t rely on it for cross-query computations.

New in version 5.0.

nodes

The pair of nodes which this relationship connects.

start_node

The start node of this relationship.

end_node

The end node of this relationship.

type

The type name of this relationship. This is functionally equivalent to type(relationship).__name__.

get(name, default=None)

Get a property value by name, optionally with a default.

Parameters
Return type

Any

keys()

Return an iterable of all property names.

Return type

KeysView[str]

values()

Return an iterable of all property values.

Return type

ValuesView[Any]

items()

Return an iterable of all property name-value pairs.

Return type

ItemsView[str, Any]

Path

class neo4j.graph.Path(start_node, *relationships)

Self-contained graph path.

Parameters
Return type

None

path == other

Compares paths for equality.

path != other

Compares paths for inequality.

hash(path)

Computes the hash of a path.

len(path)

Returns the number of relationships in a path.

iter(path)

Iterates through all the relationships in a path.

graph

The Graph to which this path belongs.

nodes

The sequence of Node objects in this path.

start_node

The first Node in this path.

end_node

The last Node in this path.

relationships

The sequence of Relationship objects in this path.

Spatial Data Types

Cypher has built-in support for handling spatial values (points), and the underlying database supports storing these point values as properties on nodes and relationships.

https://neo4j.com/docs/cypher-manual/current/syntax/spatial/

Cypher Type

Python Type

Point

neo4j.spatial.Point

Point (Cartesian)

neo4j.spatial.CartesianPoint

Point (WGS-84)

neo4j.spatial.WGS84Point

See topic Spatial Data Types for more details.

Temporal Data Types

Temporal data types are implemented by the neo4j.time module.

It provides a set of types compliant with ISO-8601 and Cypher, which are similar to those found in the built-in datetime module. Sub-second values are measured to nanosecond precision and the types are compatible with pytz.

The table below shows the general mappings between Cypher and the temporal types provided by the driver.

In addition, the built-in temporal types can be passed as parameters and will be mapped appropriately.

Cypher

Python driver type

Python built-in type

tzinfo

Date

neo4j.time.Date

datetime.date

Time

neo4j.time.Time

datetime.time

not None

LocalTime

neo4j.time.Time

datetime.time

None

DateTime

neo4j.time.DateTime

datetime.datetime

not None

LocalDateTime

neo4j.time.DateTime

datetime.datetime

None

Duration

neo4j.time.Duration

datetime.timedelta

Sub-second values are measured to nanosecond precision and the types are mostly compatible with pytz. Some timezones (e.g., pytz.utc) work exclusively with the built-in datetime.datetime.

Note

Cypher has built-in support for handling temporal values, and the underlying database supports storing these temporal values as properties on nodes and relationships, see https://neo4j.com/docs/cypher-manual/current/syntax/temporal/

See topic Temporal Data Types for more details.

BookmarkManager

class neo4j.api.BookmarkManager

Class to manage bookmarks throughout the driver’s lifetime.

Neo4j clusters are eventually consistent, meaning that there is no guarantee a query will be able to read changes made by a previous query. For cases where such a guarantee is necessary, the server provides bookmarks to the client. A bookmark is an abstract token that represents some state of the database. By passing one or multiple bookmarks along with a query, the server will make sure that the query will not get executed before the represented state(s) (or a later state) have been established.

The bookmark manager is an interface used by the driver for keeping track of the bookmarks and this way keeping sessions automatically consistent. Configure the driver to use a specific bookmark manager with bookmark_manager.

This class is just an abstract base class that defines the required interface. Create a child class to implement a specific bookmark manager or make use of the default implementation provided by the driver through GraphDatabase.bookmark_manager().

Note

All methods must be concurrency safe.

Generally, all methods need to be able to cope with getting passed a database parameter that is (until then) unknown to the manager.

New in version 5.0.

abstract update_bookmarks(database, previous_bookmarks, new_bookmarks)

Handle bookmark updates.

Parameters
  • database (str) – The database which the bookmarks belong to

  • previous_bookmarks (Collection[str]) – The bookmarks used at the start of a transaction

  • new_bookmarks (Collection[str]) – The new bookmarks retrieved at the end of a transaction

Return type

None

abstract get_bookmarks(database)

Return the bookmarks for a given database.

Parameters

database (str) – The database which the bookmarks belong to

Returns

The bookmarks for the given database

Return type

Collection[str]

abstract get_all_bookmarks()

Return all bookmarks for all known databases.

Returns

The collected bookmarks.

Return type

Collection[str]

abstract forget(databases)

Forget the bookmarks for the given databases.

This method is not called by the driver. Forgetting unused databases is the user’s responsibility.

Parameters

databases (Iterable[str]) – The databases which the bookmarks will be removed for.

Return type

None

Errors

Neo4j Errors

Server-side errors

exception neo4j.exceptions.Neo4jError

Bases: Exception

Raised when the Cypher engine returns an error to the client.

message = None

(str or None) The error message returned by the server.

code = None

(str or None) The error code returned by the server. There are many Neo4j status codes, see status codes.

is_retriable()

Whether the error is retryable.

See is_retryable().

Returns

True if the error is retryable, False otherwise.

Return type

bool

Deprecated since version 5.0: This method will be removed in a future version. Please use is_retryable() instead.

is_retryable()

Whether the error is retryable.

Indicates whether a transaction that yielded this error makes sense to retry. This method makes mostly sense when implementing a custom retry policy in conjunction with Explicit Transactions.

Returns

True if the error is retryable, False otherwise.

Return type

bool

exception neo4j.exceptions.ClientError

Bases: neo4j.exceptions.Neo4jError

The Client sent a bad request - changing the request might yield a successful outcome.

exception neo4j.exceptions.CypherSyntaxError

Bases: neo4j.exceptions.ClientError

exception neo4j.exceptions.CypherTypeError

Bases: neo4j.exceptions.ClientError

exception neo4j.exceptions.ConstraintError

Bases: neo4j.exceptions.ClientError

exception neo4j.exceptions.AuthError

Bases: neo4j.exceptions.ClientError

Raised when authentication failure occurs.

exception neo4j.exceptions.TokenExpired

Bases: neo4j.exceptions.AuthError

Raised when the authentication token has expired.

A new driver instance with a fresh authentication token needs to be created.

exception neo4j.exceptions.Forbidden

Bases: neo4j.exceptions.ClientError

exception neo4j.exceptions.DatabaseError

Bases: neo4j.exceptions.Neo4jError

The database failed to service the request.

exception neo4j.exceptions.TransientError

Bases: neo4j.exceptions.Neo4jError

The database cannot service the request right now, retrying later might yield a successful outcome.

exception neo4j.exceptions.DatabaseUnavailable

Bases: neo4j.exceptions.TransientError

exception neo4j.exceptions.NotALeader

Bases: neo4j.exceptions.TransientError

exception neo4j.exceptions.ForbiddenOnReadOnlyDatabase

Bases: neo4j.exceptions.TransientError

Driver Errors

Client-side errors

exception neo4j.exceptions.DriverError

Bases: Exception

Raised when the Driver raises an error.

is_retryable()

Whether the error is retryable.

Indicates whether a transaction that yielded this error makes sense to retry. This method makes mostly sense when implementing a custom retry policy in conjunction with Explicit Transactions.

Returns

True if the error is retryable, False otherwise.

Return type

bool

exception neo4j.exceptions.SessionError

Bases: neo4j.exceptions.DriverError

Raised when an error occurs while using a session.

session: _T_Session
exception neo4j.exceptions.TransactionError

Bases: neo4j.exceptions.DriverError

Raised when an error occurs while using a transaction.

transaction: _T_Transaction
exception neo4j.exceptions.TransactionNestingError

Bases: neo4j.exceptions.TransactionError

Raised when transactions are nested incorrectly.

exception neo4j.exceptions.ResultError

Bases: neo4j.exceptions.DriverError

Raised when an error occurs while using a result object.

result: _T_Result
exception neo4j.exceptions.ResultConsumedError

Bases: neo4j.exceptions.ResultError

Raised when trying to access records of a consumed result.

exception neo4j.exceptions.ResultNotSingleError

Bases: neo4j.exceptions.ResultError

Raised when a result should have exactly one record but does not.

exception neo4j.exceptions.BrokenRecordError

Bases: neo4j.exceptions.DriverError

Raised when accessing a Record’s field that couldn’t be decoded.

This can for instance happen when the server sends a zoned datetime with a zone id unknown to the client.

exception neo4j.exceptions.SessionExpired

Bases: neo4j.exceptions.DriverError

Raised when a session is no longer able to fulfil the purpose described by its original parameters.

exception neo4j.exceptions.ServiceUnavailable

Bases: neo4j.exceptions.DriverError

Raised when no database service is available.

This may be due to incorrect configuration or could indicate a runtime failure of a database service that the driver is unable to route around.

exception neo4j.exceptions.RoutingServiceUnavailable

Bases: neo4j.exceptions.ServiceUnavailable

Raised when no routing service is available.

exception neo4j.exceptions.WriteServiceUnavailable

Bases: neo4j.exceptions.ServiceUnavailable

Raised when no write service is available.

exception neo4j.exceptions.ReadServiceUnavailable

Bases: neo4j.exceptions.ServiceUnavailable

Raised when no read service is available.

exception neo4j.exceptions.IncompleteCommit

Bases: neo4j.exceptions.ServiceUnavailable

Raised when the client looses connection while committing a transaction

Raised when a disconnection occurs while still waiting for a commit response. For non-idempotent write transactions, this leaves the data in an unknown state with regard to whether the transaction completed successfully or not.

exception neo4j.exceptions.ConfigurationError

Bases: neo4j.exceptions.DriverError

Raised when there is an error concerning a configuration.

exception neo4j.exceptions.AuthConfigurationError

Bases: neo4j.exceptions.ConfigurationError

Raised when there is an error with the authentication configuration.

exception neo4j.exceptions.CertificateConfigurationError

Bases: neo4j.exceptions.ConfigurationError

Raised when there is an error with the certificate configuration.

Internal Driver Errors

If an internal error (BoltError), in particular a protocol error (BoltProtocolError) is surfaced please open an issue on github.

https://github.com/neo4j/neo4j-python-driver/issues

Please provide details about your running environment,

  • Operating System:

  • Python Version:

  • Python Driver Version:

  • Neo4j Version:

  • The code block with a description that produced the error:

  • The error message:

Warnings

The Python Driver uses the built-in DeprecationWarning class to warn about deprecations.

The Python Driver uses the neo4j.ExperimentalWarning class to warn about experimental features.

class neo4j.ExperimentalWarning

Base class for warnings about experimental features.

Filter Warnings

This example shows how to suppress the neo4j.ExperimentalWarning using the warnings.filterwarnings() function.

import warnings
from neo4j import ExperimentalWarning

...

with warnings.catch_warnings():
    warnings.filterwarnings("ignore", category=ExperimentalWarning)
    ...  # the call emitting the ExperimentalWarning

...

This will only mute the neo4j.ExperimentalWarning for everything inside the with-block. This is the preferred way to mute warnings, as warnings triggerd by new code will still be visible.

However, should you want to mute it for the entire application, use the following code:

import warnings
from neo4j import ExperimentalWarning

warnings.filterwarnings("ignore", category=ExperimentalWarning)

...

Logging

The driver offers logging for debugging purposes. It is not recommended to enable logging for anything other than debugging. For instance, if the driver is not able to connect to the database server or if undesired behavior is observed.

There are different ways of enabling logging as listed below.

Note

For an improved logging experience with the async driver, please see Async Logging.

Simple Approach

neo4j.debug.watch(*logger_names, level=logging.DEBUG, out=sys.stderr, colour=False)

Quick wrapper for using Watcher.

Create a Watcher with the given configuration, enable watching and return it.

Example:

from neo4j.debug import watch

watch("neo4j")
# from now on, DEBUG logging to stderr is enabled in the driver

Note

The exact logging format is not part of the API contract and might change at any time without notice. It is meant for debugging purposes and human consumption only.

Parameters
  • logger_names (Optional[str]) – Names of loggers to watch.

  • level (int) – see default_level of Watcher.

  • out (stream or file-like object) – see default_out of Watcher.

  • colour (bool) – see colour of Watcher.

  • thread_info (bool) – see thread_info of Watcher.

  • task_info (bool) – see task_info of Watcher.

Returns

Watcher instance

Return type

Watcher

Changed in version 5.3:

  • Added thread_info and task_info parameters.

  • Logging format around thread and task information changed.

Context Manager

class neo4j.debug.Watcher(*logger_names, default_level=logging.DEBUG, default_out=sys.stderr, colour=False)

Log watcher for easier logging setup.

Example:

from neo4j.debug import Watcher

with Watcher("neo4j"):
    # DEBUG logging to stderr enabled within this context
    ...  # do something

Note

The Watcher class is not thread-safe. Having Watchers in multiple threads can lead to duplicate log messages as the context manager will enable logging for all threads.

Note

The exact logging format is not part of the API contract and might change at any time without notice. It is meant for debugging purposes and human consumption only.

Parameters
  • logger_names (t.Optional[str]) – Names of loggers to watch.

  • default_level (int) – Default minimum log level to show. The level can be overridden by setting level when calling watch().

  • default_out (stream or file-like object) – Default output stream for all loggers. The level can be overridden by setting out when calling watch().

  • colour (bool) – Whether the log levels should be indicated with ANSI colour codes.

  • thread_info (bool) – whether to include information about the current thread in the log message. Defaults to True.

  • task_info (bool) – whether to include information about the current async task in the log message. Defaults to True.

Return type

None

Changed in version 5.3:

  • Added thread_info and task_info parameters.

  • Logging format around thread and task information changed.

__enter__()

Enable logging for all loggers.

Return type

neo4j.debug.Watcher

__exit__(exc_type, exc_val, exc_tb)

Disable logging for all loggers.

watch(level=None, out=None)

Enable logging for all loggers.

Parameters
  • level (Optional[int]) – Minimum log level to show. If None, the default_level is used.

  • out (stream or file-like object) – Output stream for all loggers. If None, the default_out is used.

Return type

None

stop()

Disable logging for all loggers.

Return type

None

Full Control

import logging
import sys

# create a handler, e.g. to log to stdout
handler = logging.StreamHandler(sys.stdout)
# configure the handler to your liking
handler.setFormatter(logging.Formatter(
    "[%(levelname)-8s] %(threadName)s(%(thread)d) %(asctime)s  %(message)s"
))
# add the handler to the driver's logger
logging.getLogger("neo4j").addHandler(handler)
# make sure the logger logs on the desired log level
logging.getLogger("neo4j").setLevel(logging.DEBUG)
# from now on, DEBUG logging to stdout is enabled in the driver

Bookmarks

class neo4j.Bookmarks

Container for an immutable set of bookmark string values.

Bookmarks are used to causally chain session. See Session.last_bookmarks() or AsyncSession.last_bookmarks() for more information.

Use addition to combine multiple Bookmarks objects:

bookmarks3 = bookmarks1 + bookmarks2
__bool__()

True if there are bookmarks in the container.

Return type

bool

__add__(other)

Add multiple containers together.

Parameters

other (neo4j.api.Bookmarks) –

Return type

neo4j.api.Bookmarks

property raw_values: FrozenSet[str]

The raw bookmark values.

You should not need to access them unless you want to serialize bookmarks.

Returns

immutable list of bookmark string values

Return type

frozenset[str]

classmethod from_raw_values(values)

Create a Bookmarks object from a list of raw bookmark string values.

You should not need to use this method unless you want to deserialize bookmarks.

Parameters

values (Iterable[str]) – ASCII string values (raw bookmarks)

Return type

neo4j.api.Bookmarks

class neo4j.Bookmark(*values)

A Bookmark object contains an immutable list of bookmark string values.

Deprecated since version 5.0: Bookmark will be removed in version 6.0. Use Bookmarks instead.

Parameters

values (str) – ASCII string values

Return type

None

property values: frozenset
Returns

immutable list of bookmark string values