Skip to content

Persistence

Saving and loading a KnowledgeGraph as JSON, with legacy compatibility.

Documents are wrapped in a versioned envelope {schema_version, graph}. Schema version 4 is the generic {nodes, edges} shape; versions 1-3 are the legacy five-collection provenance shape, which is transparently converted on load via :func:~ideagraph.kg.profiles.research_compat.graph_from_legacy, so files written by the old core still open.

dumps_graph(graph, *, indent=2)

Serialise a graph to a JSON string.

Parameters:

Name Type Description Default
graph KnowledgeGraph

The graph to serialise.

required
indent int

Indentation passed to :func:json.dumps.

2

Returns:

Type Description
str

The JSON document.

Source code in src/ideagraph/kg/persistence.py
64
65
66
67
68
69
70
71
72
73
74
75
def dumps_graph(graph: KnowledgeGraph, *, indent: int = 2) -> str:
    """Serialise a graph to a JSON string.

    Args:
        graph: The graph to serialise.
        indent: Indentation passed to :func:`json.dumps`.

    Returns:
        The JSON document.

    """
    return json.dumps(graph_to_document(graph), indent=indent, ensure_ascii=False)

graph_from_document(document)

Reconstruct a graph from a versioned envelope (any supported version).

Parameters:

Name Type Description Default
document dict[str, Any]

A dictionary with schema_version and graph.

required

Returns:

Type Description
KnowledgeGraph

The reconstructed generic graph.

Raises:

Type Description
KeyError

If the envelope is missing required keys.

ValueError

If the schema_version is newer than supported.

Source code in src/ideagraph/kg/persistence.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def graph_from_document(document: dict[str, Any]) -> KnowledgeGraph:
    """Reconstruct a graph from a versioned envelope (any supported version).

    Args:
        document: A dictionary with ``schema_version`` and ``graph``.

    Returns:
        The reconstructed generic graph.

    Raises:
        KeyError: If the envelope is missing required keys.
        ValueError: If the ``schema_version`` is newer than supported.

    """
    version = document["schema_version"]
    graph = document["graph"]
    if version > SCHEMA_VERSION:
        raise ValueError(
            f"document schema_version {version} is newer than supported version {SCHEMA_VERSION}; upgrade ideagraph"
        )
    if version <= _LEGACY_MAX:
        return graph_from_legacy(graph)
    return KnowledgeGraph.from_dict(graph)

graph_to_document(graph)

Wrap a graph's serialised form in a versioned envelope.

Parameters:

Name Type Description Default
graph KnowledgeGraph

The graph to wrap.

required

Returns:

Type Description
dict[str, Any]

A dictionary with schema_version and graph keys.

Source code in src/ideagraph/kg/persistence.py
26
27
28
29
30
31
32
33
34
35
36
def graph_to_document(graph: KnowledgeGraph) -> dict[str, Any]:
    """Wrap a graph's serialised form in a versioned envelope.

    Args:
        graph: The graph to wrap.

    Returns:
        A dictionary with ``schema_version`` and ``graph`` keys.

    """
    return {"schema_version": SCHEMA_VERSION, "graph": graph.to_dict()}

load_graph(path)

Read a graph from a JSON file (generic or legacy).

Parameters:

Name Type Description Default
path str | Path

Source file path.

required

Returns:

Type Description
KnowledgeGraph

The reconstructed graph.

Source code in src/ideagraph/kg/persistence.py
106
107
108
109
110
111
112
113
114
115
116
def load_graph(path: str | Path) -> KnowledgeGraph:
    """Read a graph from a JSON file (generic or legacy).

    Args:
        path: Source file path.

    Returns:
        The reconstructed graph.

    """
    return loads_graph(Path(path).read_text(encoding="utf-8"))

loads_graph(text)

Deserialise a graph from a JSON string.

Parameters:

Name Type Description Default
text str

A JSON document as produced by :func:dumps_graph (or a legacy document from the old core).

required

Returns:

Type Description
KnowledgeGraph

The reconstructed graph.

Source code in src/ideagraph/kg/persistence.py
78
79
80
81
82
83
84
85
86
87
88
89
def loads_graph(text: str) -> KnowledgeGraph:
    """Deserialise a graph from a JSON string.

    Args:
        text: A JSON document as produced by :func:`dumps_graph` (or a legacy
            document from the old core).

    Returns:
        The reconstructed graph.

    """
    return graph_from_document(json.loads(text))

save_graph(graph, path, *, indent=2)

Write a graph to a JSON file, creating parent directories as needed.

Parameters:

Name Type Description Default
graph KnowledgeGraph

The graph to save.

required
path str | Path

Destination file path.

required
indent int

Indentation passed to :func:json.dumps.

2
Source code in src/ideagraph/kg/persistence.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def save_graph(graph: KnowledgeGraph, path: str | Path, *, indent: int = 2) -> None:
    """Write a graph to a JSON file, creating parent directories as needed.

    Args:
        graph: The graph to save.
        path: Destination file path.
        indent: Indentation passed to :func:`json.dumps`.

    """
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(dumps_graph(graph, indent=indent) + "\n", encoding="utf-8")