Exchange current graphs with NetworkX and GEXF

Use this adapter to move a materialized current graph between GestaltDB and NetworkX, or load a supported static GEXF file into a database. Choose the mapping before import: a display label is not necessarily a native graph label, and an XML edge ID is not a relationship type. Historical claims, reasoning state and sampler arrays are not implicitly converted.

Install the optional adapter and a backend, for example:

1pip install 'gestaltdb[networkx,lmdb]'

Import helpers from gestaltdb.integrations.networkx. NetworkX and defusedxml are loaded lazily; importing GestaltDB or the integration module does not require them. No live NetworkX backend or algorithm dispatch is installed: algorithms operate on a materialized export of current records.

Choose the exchange boundary

Task

API

Important limit

Import an in-memory NetworkX graph

from_networkx

No update/merge mode; existing-ID collisions reject

Run NetworkX algorithms on stored records

to_networkx then ordinary NetworkX calls

Full in-memory export, not live algorithm dispatch or an automatic snapshot

Load a local static GEXF file

load_gexf

Local XML only; dynamics and GEXF writing are not supported

Imports preflight before writing but are not one atomic import transaction. Completed batches can survive a later failure. Quiesce writers for consistent exchange; selecting a backend with transactions does not change this batch-level contract. See the failure and memory/security sections below.

NetworkX algorithm round trip

Standalone example. Choose the capability-qualified installation tab below.

This fixture uses values compatible with all listed codecs. Arbitrary NetworkX attributes need their own codec compatibility checks.

1python -m pip install "gestaltdb[lmdb,networkx]"
 1from tempfile import TemporaryDirectory
 2import networkx as nx
 3from gestaltdb.graphdb import GraphDB
 4from gestaltdb.integrations.networkx import from_networkx, to_networkx
 5
 6source = nx.MultiDiGraph(name="people")
 7source.add_node("alice", category="Person", name="Alice")
 8source.add_node("bob", category="Person", name="Bob")
 9source.add_node("carol", category="Person", name="Carol")  # isolated node
10source.add_edge("alice", "bob", key="friend", id="e1", relation="KNOWS")
11source.add_edge("alice", "bob", key="colleague", id="e2", relation="KNOWS")
12source.add_edge("bob", "bob", key="self", id="e3", relation="KNOWS")
13
14with TemporaryDirectory() as directory:
15    graph = GraphDB.create(directory + "/db", backend='lmdb', serializer='json')
16    try:
17        result = from_networkx(
18            source, graph,
19            node_labels_attribute="category", edge_type_attribute="relation",
20        )
21        exported = to_networkx(graph, graph_attributes=result.graph_attributes)
22        assert nx.shortest_path(exported, "alice", "bob") == ["alice", "bob"]
23        assert exported.edges["alice", "bob", "friend"]["type"] == "KNOWS"
24        assert "carol" in exported and exported.number_of_edges() == 3
25        assert exported.has_edge("bob", "bob", "self")
26        with GraphDB.create(directory + "/copy", backend='lmdb', serializer='json') as copy:
27            restored = from_networkx(exported, copy)
28            assert restored.imported_nodes == 3 and restored.imported_edges == 3
29            assert set(copy.get_node(b"alice").labels) == {"Person"}
30    finally:
31        graph.close()

Static GEXF loading

load_gexf accepts a local path (including .gz and .bz2) or an already decompressed binary stream. It never fetches URLs and never closes a supplied stream. The caller owns the destination GraphDB handle.

Standalone example. Choose the capability-qualified installation tab below.

Static GEXF loading keeps the mapping/security limits regardless of backend choice.

1python -m pip install "gestaltdb[lmdb,networkx]"
 1from io import BytesIO
 2from tempfile import TemporaryDirectory
 3from gestaltdb.graphdb import GraphDB
 4from gestaltdb.integrations.networkx import load_gexf, to_networkx
 5
 6data = b'''<gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">
 7  <graph defaultedgetype="directed" mode="static">
 8    <nodes><node id="alice" label="Alice"/><node id="bob" label="Bob"/></nodes>
 9    <edges><edge id="e1" source="alice" target="bob" weight="2.5"/></edges>
10  </graph>
11</gexf>'''
12with TemporaryDirectory() as directory:
13    graph = GraphDB.create(directory + "/db", backend='lmdb', serializer='json')
14    try:
15        result = load_gexf(BytesIO(data), graph, label_property="name")
16        assert result.imported_nodes == 2 and result.imported_edges == 1
17        assert graph.get_node(b"alice").properties["name"] == "Alice"
18        exported = to_networkx(graph, graph_attributes=result.graph_attributes)
19        assert set(exported.nodes) == {"alice", "bob"}
20        assert next(iter(exported.edges(data=True)))[2]["weight"] == 2.5
21    finally:
22        graph.close()

Supported format matrix

Input

Behavior

NetworkX DiGraph/MultiDiGraph

Directed import; isolated nodes and loops kept

NetworkX Graph/MultiGraph

Reject unless undirected="bidirectional"

GEXF 1.1draft and 1.2draft

Static graphs using their standard namespaces

GEXF attributes

Reader-supported scalar types; defaults applied

GEXF node visualization

Color, size, thickness, shape, position properties

GEXF graph metadata

Name, mode, defaults and root meta in result

GEXF dynamics/spells/slices

Rejected; no implicit temporal-history mapping

Mixed/mutual edge direction

Rejected

Hierarchy/hyperedges/extensions

Rejected rather than silently ignored

GEXF edge visualization

Rejected (not preserved by the NetworkX reader)

GEXF writing

Not provided

GEXF id remains node identity; label becomes a display property (label by default, configurable with label_property), not a native GestaltDB label. Edge IDs and weights remain properties as well as serving their identity/weight roles. Relationship types are not inferred from edge IDs, labels, or keys. Static attribute definitions with duplicate IDs/titles or reserved reader fields fail clearly. Duplicate node IDs, edge IDs, multiedge keys, undeclared endpoints, and unsupported XML fields also fail before writes. Root meta is included under result.graph_attributes['gexf_meta'].

Mapping policies

  • Node IDs: Nonempty string keys are kept. Other finite scalar or tuple keys use tagged, SHA-256-derived IDs, distinguishing e.g. 1 and "1". node_id(key) -> str overrides ID generation and enables custom hashable objects; custom objects export as their mapped ID, with a result warning. Mapped IDs must be nonempty UTF-8 strings of at most 255 bytes. All collisions within the input or against the destination are errors. No update/merge mode is provided.

  • Edge IDs: The id property (configurable via edge_id_attribute) is preserved when present and must satisfy the same string ID contract. Otherwise IDs hash mapped endpoints and a tagged multigraph key. Generated undirected IDs use canonically ordered endpoints. Multigraph keys may be finite scalars or tuples; arbitrary key objects are not supported.

  • Undirected edges: Explicit bidirectional expansion writes two directed edges, or one for a self-loop. Reverse edge IDs are deterministically derived. The export remains directed; undirected storage semantics are not implied.

  • Labels/types: node_labels_attribute selects a string or list of nonempty strings. edge_type_attribute defaults to type and can select another nonempty string property. A conflicting existing type is an error. Missing attributes mean no additional native labels/relationship type. Original source properties are retained.

  • Attributes: Import accepts string-keyed dictionaries, lists, None, booleans, integers, strings and finite floats. Tuples as property values, sets, arbitrary objects, non-string dictionary keys and nonfinite floats require explicit attribute_transform(kind, attrs) -> dict conversion. kind is node, edge or graph. Transforms receive copies and produce a warning; source graphs are never mutated. The destination serializer is exercised during preflight, including its numeric limits.

  • Reserved metadata: __gestaltdb_networkx__ is a reserved property and NetworkX attribute namespace. Stored metadata contains tagged original keys; exported node metadata contains id/labels, and edge metadata contains id. This allows reimport of adapter exports with stable IDs and native labels. Do not use this namespace for application attributes. Malformed or conflicting metadata is rejected, not overwritten. Simple source edges have no multigraph key; their exported key is their stored edge ID.

  • Graph attributes: Returned in ImportResult.graph_attributes, not persisted as hidden nodes or database metadata. Pass them explicitly as to_networkx(..., graph_attributes=result.graph_attributes) to restore them.

Export and selections

to_networkx(graph) creates a MultiDiGraph including isolated nodes. multigraph=False creates a DiGraph only if no parallel edges would be lost; reduction policies are deliberately not implicit. Duplicate original keys or dangling endpoints are errors. Exported property dictionaries are copies.

node_ids=[...] selects an induced subgraph using stored GestaltDB IDs. edge_ids=[...] selects edges and their endpoints. With both, all selected edge endpoints must be selected nodes. Missing explicitly selected IDs fail. Only current mutable graph records are exported: not claims, rules, temporal versions or sampler history. Exports do not automatically pin a read snapshot; quiesce writers when a consistent materialized view is needed.

Import results, indexes and failures

ImportResult reports source/imported counts, node-ID mappings, edge_ids[(source, target, key)] tuples of written edge IDs (simple source graphs use key None), graph attributes, warnings, and direction conversion.

Imports prepare all records and check mappings, existing IDs, attributes, serializer compatibility and encoded index-key limits before writing. Native label, relationship-type, adjacency and configured property indexes are maintained through graph.nodes.put_many/graph.edges.put_many; no deferred rebuild is needed. Configure explicit property indexes before import when required.

Writes use batch_size=1000 by default. Each batch inherits the backend’s normal write/transaction guarantees. The import is not one atomic transaction on any backend; completed batches survive later failures. ImportWriteError provides result (completed-batch counts), phase, batch_start and the underlying exception as its cause. The failing batch may also have partial writes on nontransactional storage. Inspect the destination before retrying. Quiesce other writers during imports: preflight is not a concurrent uniqueness constraint. The adapter never closes or replaces the caller’s database.

Memory and XML security

NetworkX loading and export fully materialize graphs. Import also prepares entity records in memory. Batching destination writes is not streaming or out-of-core loading.

GEXF is parsed first by defusedxml with document type declarations (DTDs), entities and external references forbidden; only the validated, sanitized tree reaches NetworkX. max_bytes defaults to 64 MiB and limits decompressed XML, including compressed paths. Caller-owned streams must implement normal bounded read(size) semantics. XML/tree/attribute expansion and graph objects still consume more memory than the input; there is no CPU or total-memory quota. Use appropriately small limits and process isolation for adversarial inputs.

API reference

Materialized NetworkX conversion and hardened static GEXF loading.

Install gestaltdb[networkx]. These helpers never close the caller’s database. See docs/networkx.rst for the mapping and partial-write contracts.

class gestaltdb.integrations.networkx.ImportResult(source_nodes, source_edges, imported_nodes=0, imported_edges=0, node_ids=<factory>, edge_ids=<factory>, graph_attributes=<factory>, warnings=<factory>, direction_conversion='none')[source]

Import counts and mappings; graph attributes are returned, not persisted.

edge_ids[(source, target, key)] contains one ID for directed edges and one or two IDs for bidirectional expansion. Simple graphs use key None.

Parameters:
exception gestaltdb.integrations.networkx.ImportWriteError(result, phase, batch_start)[source]

A write failed. Completed batches are in result; the failing batch may also have written data. Quiesce other writers and inspect before retrying.

Parameters:
gestaltdb.integrations.networkx.from_networkx(graph, target, *, node_id=None, edge_id_attribute='id', node_labels_attribute=None, edge_type_attribute='type', undirected='reject', batch_size=1000, attribute_transform=None)[source]

Validate and import a NetworkX graph, rejecting destination ID collisions.

All entities are prepared before writes. attribute_transform(kind, attrs) explicitly converts unsupported properties; kind is node/edge/graph. Missing mapped label/type attributes mean no labels/type. A conflicting existing type property is rejected. No source attributes are removed.

Parameters:
  • graph (nx.Graph)

  • target (GraphDB)

  • node_id (Callable[[Any], str] | None)

  • edge_id_attribute (str)

  • node_labels_attribute (str | None)

  • edge_type_attribute (str | None)

  • undirected (str)

  • batch_size (int)

  • attribute_transform (Callable[[str, dict], dict] | None)

Return type:

ImportResult

gestaltdb.integrations.networkx.load_gexf(source, target, *, label_property='label', max_bytes=67108864, **kwargs)[source]

Load static GEXF 1.1draft/1.2draft from a local path or binary stream.

Paths ending in .gz/.bz2 are decompressed with a bounded read. Streams are caller-owned and must already be decompressed. No URLs or dynamic graphs. max_bytes bounds decompressed XML, not total parsing/graph memory.

Parameters:
Return type:

ImportResult

gestaltdb.integrations.networkx.to_networkx(graph, *, node_ids=None, edge_ids=None, multigraph=True, graph_attributes=None)[source]

Export current records to a MultiDiGraph (or lossless DiGraph).

node_ids selects an induced subgraph. edge_ids selects edges, adding endpoints when no node selection is given. With both, endpoints must be in the node selection. Missing selected IDs and dangling edges raise errors. Caller-supplied graph attributes are copied; they are not read from storage.

Parameters:
Return type:

nx.MultiDiGraph | nx.DiGraph

Use Explore graphs and reasoning offline to inspect selected records without installing NetworkX, Compatibility, Migration, and Recovery for database recovery, and Performance and Benchmarks to measure preflight/conversion separately from batched writes and graph algorithms.