# How to Export the Knowledge Graph from Code-Graph-RAG: A Complete Developer Guide

> Learn to export your knowledge graph from Code-Graph-RAG using the export_graph_to_file function. This guide shows developers how to save your graph data to a portable JSON file.

- Repository: [Vitali Avagyan/code-graph-rag](https://github.com/vitali87/code-graph-rag)
- Tags: how-to-guide
- Published: 2026-09-08

---

**Code-Graph-RAG provides the `export_graph_to_file` function in [`codebase_rag/main.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py) that serializes the complete knowledge graph from a `MemgraphIngestor` instance to a portable JSON file matching the protobuf schema in `codec/schema.proto`.**

Code-Graph-RAG builds knowledge graphs by parsing codebases into entities like functions, classes, and modules, storing them in Memgraph. When you need to backup this data, feed it into downstream analytics tools, or migrate between environments, exporting to a structured JSON format is the standard approach.

## How the Export Pipeline Works

The export flow relies on three core components working in sequence. First, the `MemgraphIngestor` class buffers all graph entities during the codebase parsing phase. After ingestion completes, the `export_graph_to_file` wrapper retrieves the serialized data via `export_graph_to_dict` and writes it to disk. The resulting JSON adheres to the schema defined in `codec/schema.proto`, ensuring type-safe interoperability.

Key source locations:
- **Export wrapper**: `export_graph_to_file` in [`codebase_rag/main.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py) (line 1403)
- **Ingestor implementation**: `MemgraphIngestor` class in [`codebase_rag/services/graph_service.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/graph_service.py) (line 86)
- **Protobuf schema**: `codec/schema.proto`

## Step-by-Step Export Guide

### 1. Initialize the MemgraphIngestor

Create a `MemgraphIngestor` instance using the `connect_memgraph` factory. This object manages the connection to Memgraph and buffers entities as they are parsed.

```python
from codebase_rag.main import connect_memgraph

# Create ingestor with batching for performance

ingestor = connect_memgraph(batch_size=1000)

```

### 2. Run the Ingestion Process

Populate the ingestor by processing your target codebase. This can occur via the CLI or programmatically through the library's API. Once complete, the `ingestor` instance holds all nodes and relationships in memory.

```python
from codebase_rag.cli import run

# Fill the ingestor with code entities

run(ingestor)  # Parses codebase and builds graph

```

### 3. Export to JSON

Call `export_graph_to_file`, passing the ingestor and a destination path. The function returns a boolean indicating success and logs a summary of node and relationship counts to the console.

```python
from codebase_rag.main import export_graph_to_file

success = export_graph_to_file(ingestor, "graph_export.json")

if success:
    print("✅ Graph exported successfully!")
else:
    print("❌ Export failed – check logs for details.")

```

## Understanding the Export Format

The exported JSON file contains three top-level keys defined by the protobuf schema:

- **`metadata`**: Export timestamp, total node count, total relationship count, and version information.
- **`nodes`**: Array of node objects, each containing labels, properties (name, source location, docstring, etc.), and unique identifiers.
- **`relationships`**: Array of edge objects specifying source and target nodes, relationship types (e.g., `CALLS`, `CONTAINS`), and property dictionaries.

This structure ensures compatibility with `GraphLoader` utilities and external graph analysis tools.

## Loading and Inspecting Exported Graphs

To verify or analyze an export without reconnecting to Memgraph, use the `load_graph` function from `codebase_rag/graph_loader`.

```python
from codebase_rag.graph_loader import load_graph

# Load the exported JSON

graph = load_graph("graph_export.json")

# Retrieve statistics

summary = graph.summary()
print(f"Nodes: {summary['total_nodes']}")
print(f"Relationships: {summary['total_relationships']}")

```

For a ready-made inspection tool, use the example script provided in the repository:

```bash
python examples/graph_export_example.py path/to/graph_export.json

```

This script demonstrates best practices for loading via `GraphLoader` and printing node relationship statistics.

## Summary

- **Primary function**: Use `export_graph_to_file` in [`codebase_rag/main.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py) to write the knowledge graph to JSON after ingestion completes.
- **Data source**: The `MemgraphIngestor` class in [`codebase_rag/services/graph_service.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/graph_service.py) buffers entities and provides `export_graph_to_dict` for serialization.
- **Format compliance**: Exported files follow the protobuf schema in `codec/schema.proto`, containing structured `metadata`, `nodes`, and `relationships`.
- **Verification**: Load exports using `load_graph` from `codebase_rag/graph_loader` or the reference implementation in [`examples/graph_export_example.py`](https://github.com/vitali87/code-graph-rag/blob/main/examples/graph_export_example.py).

## Frequently Asked Questions

### What format does Code-Graph-RAG use for exported knowledge graphs?

Code-Graph-RAG exports to a JSON file that complies with the protobuf schema defined in `codec/schema.proto`. The file contains three main sections: `metadata` (timestamps and counts), `nodes` (code entities with properties), and `relationships` (edges connecting entities).

### Can I export the knowledge graph without running a full ingestion?

No. The `export_graph_to_file` function requires a populated `MemgraphIngestor` instance, which only contains data after the codebase parsing process completes. You must run the ingestion pipeline first to buffer entities before exporting.

### How do I load an exported graph for offline analysis?

Import `load_graph` from `codebase_rag/graph_loader` and pass the JSON file path. This returns a graph object with a `summary()` method that returns node and relationship counts. The [`examples/graph_export_example.py`](https://github.com/vitali87/code-graph-rag/blob/main/examples/graph_export_example.py) script provides a complete reference implementation for loading and inspecting exports.

### Where is the core export logic implemented?

The high-level wrapper `export_graph_to_file` resides in [`codebase_rag/main.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py) at line 1403. This function calls `export_graph_to_dict` on the `MemgraphIngestor` instance, which is implemented in [`codebase_rag/services/graph_service.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/graph_service.py) at line 86.