NetworkX backend
drm.networkx_graph provides the in-memory backend used for tests,
examples, and lightweight local experimentation. It mirrors the public graph
store API so tutorials can switch between backends with minimal code changes.
NetworkX-backed graph store — in-memory, no real Neo4j required.
- class drm.networkx_graph.NetworkXGraph(persistence_path=None)[source]
Bases:
GraphStoreIn-memory graph store using NetworkX.
Provides the same public interface as
Neo4jGraphbut stores nodes and edges in a NetworkX MultiDiGraph so tests can run without a real database.- Parameters:
persistence_path (Optional[str])
- __init__(persistence_path=None)[source]
- Parameters:
persistence_path (str | None)
- Return type:
None
- insertNode(node, insert_parent=True, update=False, replace=False, **kwargs)[source]
Insert a node into the graph.
Returns the internal node id assigned by the graph.
- insertRelation(rel, update=False, replace=False, **kwargs)[source]
Insert a relation (directed edge) between two nodes.
Mirrors Neo4jGraph.insertRelation semantics:
update=True: MERGE + SET — adds/updates attributes without deleting the relation.update=False+replace=True: deletes the existing relation and creates a fresh one.update=False+replace=False: creates a new relation. If one with the same src/dst/type already exists, raisesRuntimeError(duplicate key).
Returns the internal edge identifier (u, v, key).
- deleteNode(node, propagation=False, detach=False, on_delete='cascade')[source]
Delete a node from the graph.
on_deletecontrols FK behavior:"cascade"(default): ON DELETE CASCADE — delete connected edges"restrict": ON DELETE RESTRICT — refuse if edges exist"set_null": ON DELETE SET NULL — delete node, keep neighbors
- checkNode(node, **kwargs)[source]
Check if a node exists in the graph.
Looks up the node by its
neo4j_idif set, otherwise searches bymain_labeland primary key.
- create(migration, update=False, replace=False)[source]
Bulk import nodes and relations.
Iterates over the node and relation lists, inserting each with the given
updateandreplaceflags.
- get_nodes()[source]
Alias for
get_node_ids()for backward compatibility.
- find_nodes_by_property(prop_name, value)[source]
Return node ids indexed by an exact property value match.
- debug()[source]
Return a human-readable snapshot of the graph state.
Returns a dict with keys: -
nodes: list of (id, label, pk) -edges: list of (src_id, dst_id, rel_type, attrs) -fk_index: dict mapping node_id -> list of (other_id, rel_type, direction)
- query(filter_dict=None, projection=None, sort=None, limit_val=None, params=None)[source]
Query nodes using MongoDB-style filters or execute Cypher.
Hybrid API — the first argument accepts either:
dict — MongoDB-style filter matching against
main_labeland node attributes. Supports operators$eq,$ne,$gt,$gte,$lt,$lte,$in,$nin,$exists,$regex.str — a Cypher query string (
MATCH,CREATE,DELETE,SET,RETURN,ORDER BY,LIMIT, aggregations, parameter substitution via$name).
- Parameters:
filter_dict (Dict[str, Any] | str | None) – Filter dict for MongoDB-style queries, or Cypher string for Cypher-style queries.
projection (Dict[str, int] | None) – Dict of fields to include (1) or exclude (0). Ignored for Cypher queries.
sort (Tuple[str, int] | None) – Tuple of
(field_name, direction)where direction is1(ascending) or-1(descending). Ignored for Cypher queries.limit_val (int | None) – Maximum number of results to return. Ignored for Cypher queries.
params (Dict[str, Any] | None) – Optional parameter dict for
$namesubstitution in Cypher queries. Ignored for MongoDB-style queries.
- Returns:
A list of dicts, one per matching node (MongoDB-style) or one per result record (Cypher-style).
- Return type:
Example
>>> # MongoDB-style >>> graph.query({"age": {"$gt": 25}}) >>> # Cypher-style >>> graph.query("MATCH (n:Person) RETURN n")
- query_nodes(filter_dict=None)[source]
Return an
NxQueryfluent builder.Unlike
query(), this returns a lazy, chainable query object instead of a list. Call.where(...),.limit(...),.count(),.to_list(), or.ids()to materialise.- Parameters:
filter_dict (Optional[Dict[str, Any]]) – Optional initial MongoDB-style filter.
- Returns:
An
NxQueryinstance over all (or filtered) nodes.- Return type:
NxQuery
Example
>>> (graph.query_nodes() ... .where({"main_label": "Person"}) ... .where({"age": {"$gte": 30}}) ... .limit(10) ... .to_list())
- schema_yaml(db_name)[source]
Introspect the database and return a YAML schema description.
Scans
_node_attrsand_edge_attrsto collect all labels, properties, relationship types, and counts. Generates Python class names from labels and relationship types.WeakNode detection: labels whose PK fields are a proper superset of another label’s PK fields are inferred as children (WeakNode). The child-specific PK fields are the set difference.
- create_group(strong_node, weak_nodes=None, weak_relations=None, **kwargs)[source]
Create a strong node together with its WeakNodes and WeakRelations atomically.
Takes a snapshot of the graph state before any modifications. If any insertion fails, the snapshot is restored so the graph is left unchanged.
- Parameters:
- Returns:
The internal id of the
strong_node.- Raises:
RuntimeError – If any part of the group creation fails.
- Return type:
- init_propagation(background=False, progress_callback=None)[source]
Scan the backend graph and initialize propagation properties.
See GraphStore.init_propagation for details.
- close()[source]
Release resources and clear the graph.
Persists the current graph state and clears in-memory data.
- Return type:
None
- enable_vector_index(property_name, dimensions, space='cosine', ef_construction=200, m=16)[source]
Enable ANN vector indexing for a given node property.
The property values must be 1D vectors with exactly
dimensionsitems.