mgclient module content¶
The module interface respects the DB-API 2.0 standard defined in PEP 249.
- mgclient.connect(*, routing=False, access_mode='WRITE', resolver=None, routing_context=None, **kwargs)¶
Open a connection to Memgraph.
Takes only keyword arguments, exactly like the C extension’s
connect().With
routing=False(the default) this is exactly the C extension’sconnect(): it opens a direct connection to the given host/port.With
routing=Trueit treats the target as a coordinator of a high-availability cluster, fetches the routing table, and returns a connection to a data instance servingaccess_mode("WRITE"-> the main,"READ"-> a replica). Aresolvermay be supplied (seeRouter) for environments where advertised addresses are not directly reachable. This is a one-shot convenience; construct aRouterdirectly to reuse the cached routing table across connections.
See Lazy connections section to learn about
advantages and limitations of using the lazy parameter.
Client-side routing¶
When connecting to a Memgraph high-availability cluster, passing
routing=True to connect() makes the connection routing-aware: the
given host/port must point at a cluster coordinator, from which the
current cluster topology is fetched (via a Bolt ROUTE message) and a data
instance matching the requested access_mode is selected and connected to.
- mgclient.ACCESS_MODE_WRITE¶
access_modevalue selecting a server that accepts writes (the cluster main). This is the default.
- mgclient.ACCESS_MODE_READ¶
access_modevalue selecting a server that serves reads (a replica).
If the addresses a cluster advertises are not directly reachable by the client
(for example when the cluster is reached through a proxy or a port-forward),
pass a resolver callable that maps an advertised "host:port" address to
an iterable of "host:port" targets to try.
connect(routing=True, ...) performs a fresh routing lookup on every call.
For a long-lived router that caches the routing table (honouring its TTL),
balances reads across replicas and fails over across coordinators, use the
Router class:
- class mgclient.Router(*, host=None, address=None, port=None, resolver=None, routing_context=None, max_retries=8, retry_backoff=1.0, retry_backoff_cap=15.0, **connect_kwargs)¶
Client-side routing engine for a Memgraph high-availability cluster.
A
Routeris created against a seed coordinator and is meant to be long-lived and reused. It fetches the cluster routing table, caches it until its TTL expires, and hands out ordinaryConnectionobjects bound to the appropriate data instance.All connection parameters other than
host/address/port(for exampleusername,passwordand the SSL options) are reused for both the coordinator and the data-instance connections.Parameters:
host/address/portThe seed coordinator to contact for the first routing-table fetch.
resolverOptional callable mapping an advertised
"host:port"address to an iterable of"host:port"targets to try, in order. Defaults to using the advertised address unchanged.routing_contextOptional
dictforwarded to the coordinator’sROUTErequest.max_retries/retry_backoff/retry_backoff_capThe managed-transaction retry budget (see
execute_read()andexecute_write()). Backoff is capped exponential:retry_backoff,2 * retry_backoff, … up toretry_backoff_capseconds.
- connect(access_mode='WRITE')¶
Open a connection to a data instance serving
access_mode.Returns an ordinary
Connection. Raisesmgclient.TransientErrorif no server for the requested access mode can be reached even after refreshing the routing table (a transient cluster condition, e.g. a failover in progress).
- execute_read(work)¶
Run
work(cursor)as a managed read against a replica.workreceives aCursorfrom a freshly routed READ connection and returns whatever the caller wants; that value is returned fromexecute_read(). On a transient cluster condition (seeis_transient_error()) the routing table is refreshed and the work is retried with capped exponential backoff, up tomax_retries.workmay be called more than once, so it should be free of side effects other than the database operations themselves.
- execute_write(work)¶
Run
work(cursor)as a managed write against the main.Like
execute_read(), but the work runs inside an explicit transaction that is committed for you, and it is routed to the main.Transient failover conditions are retried. A replication failure at commit is surfaced as an error like any other – including a SYNC “committed on the main” failure, which is not treated as success: the write is durable only on that main, so if the main is then lost before an unreachable replica catches up the write is gone. As with any retried write, make
workidempotent (e.g.MERGE) so a re-run after such an error cannot duplicate it.
- refresh()¶
Force an immediate refresh of the cached routing table.
- property routing_table¶
A snapshot of the (refreshed if absent) routing table as a dict with
"ttl","write","read"and"route"entries.
Router.execute_read() and Router.execute_write() are managed
transactions: they run your unit of work against the right instance and
automatically retry transient conditions – an instance briefly unreachable
during a failover, a replica still catching up, or a connection dropped
mid-request – with a routing refresh and capped exponential backoff. Because
the work may run more than once, make it idempotent (e.g. MERGE rather than
CREATE) so a retry cannot duplicate a write.
The classification used for retries is also exposed for building your own retry loops:
- mgclient.is_transient_error(exc)¶
True for a transient HA condition worth retrying after a short backoff.
These arise during a failover, while a replica catches up, or when an instance is dropped mid-request; they clear once the cluster reconverges.
Classification is purely by type: the driver surfaces every transient condition as
mgclient.TransientError(Memgraph’sTransientErrorBolt code, or a low-level transport/connection failure). Errors Memgraph reports asClientErrorare treated as non-transient, like any other client error.
For lower-level access to the routing table itself, see
Connection.get_routing_table().
Module constants¶
DB-API 2.0 requires the following constants to be defined:
Exceptions¶
By DB-API 2.0 specification, the module makes all error information available through these exceptions or subclasses thereof:
- exception mgclient.Warning¶
Exception raised for important warnings.
- exception mgclient.Error¶
Base class of all other error exceptions.
- exception mgclient.InterfaceError¶
Exception raised for errors related to the database interface rather than the database itself.
- exception mgclient.DatabaseError¶
Exception raised for errors related to the database.
- exception mgclient.DataError¶
Exception raised for errors that are due to problems with the processed data.
- exception mgclient.OperationalError¶
Exception raised for errors related to the database’s operation, not necessarily under the control of the programmer (e.g. unexpected disconnect, failed allocation).
- exception mgclient.TransientError¶
Exception raised for transient errors that may succeed if the operation is retried (e.g. during a high-availability failover). A subclass of
OperationalError.
- exception mgclient.IntegrityError¶
Exception raised when the relational integrity of the database is affected.
- exception mgclient.InternalError¶
Exception raised when the database encounters an internal error.
- exception mgclient.ProgrammingError¶
Exception raised for programming errors (e.g. syntax error, invalid parameters)
- exception mgclient.NotSupportedError¶
Exception raised in a case a method or database API was used which is not supported by the database.
Note
Most database errors are surfaced as DatabaseError (with
connection-related failures raised as OperationalError). Retryable
conditions such as a high-availability failover are raised as
TransientError (a subclass of OperationalError); see
is_transient_error().
Graph type objects¶
- class mgclient.Node¶
A node in the graph with optional properties and labels.
- id¶
Unique node identifier (within the scope of its origin graph).
- labels¶
A list of node labels.
- properties¶
A dictionary of node properties.
- class mgclient.Relationship¶
A directed, typed connection between two nodes with optional properties.
- id¶
Unique relationship identifier (within the scope of its origin graph).
- start_id¶
Identifier of relationship start node (or -1 if it was not supplied by the database).
- end_id¶
Identifier of relationship end node (or -1 if it was not supplied by the database).
- type¶
Relationship type.
- properties¶
A dictionary of relationship properties.
- class mgclient.Path¶
A sequence of alternating nodes and relationships corresponding to a walk in the graph.
- nodes¶
A list of nodes in the order they appear in the path. It has one element more than the
relationshipslist.