How to Export the Code‑Graph Knowledge Graph for External Analysis
Use the codebase-rag export -o <path.json> CLI command or call export_graph_to_file() programmatically to extract the full Memgraph knowledge graph into a portable JSON file containing complete node and relationship data.
The vitali87/code-graph-rag repository builds a comprehensive knowledge graph of codebases inside Memgraph, a native graph database. When you need to perform custom analytics, feed data into external visualization tools, or create versioned snapshots, you must export the knowledge graph for external analysis. The system provides both command-line and programmatic interfaces that execute read-only Cypher queries to retrieve the complete graph state and serialize it to JSON.
How the Export System Works
The export process follows a two-stage architecture that separates database retrieval from file serialization.
First, the MemgraphIngestor class in codebase_rag/services/graph_service.py contains the core retrieval method export_graph_to_dict(). This method executes two read-only Cypher queries—CYPHER_EXPORT_NODES and CYPHER_EXPORT_RELATIONSHIPS—to pull every node and relationship from Memgraph. It constructs a GraphData object and stamps it with an ISO-8601 export timestamp.
Second, the serialization layer in codebase_rag/main.py provides export_graph_to_file(), which wraps the ingestor and calls the internal helper _write_graph_json(). This helper uses json.dump(..., indent=JSON_INDENT, ensure_ascii=False) to preserve Unicode characters while producing a human-readable indented file.
Exporting the Knowledge Graph via CLI
The Typer-based CLI defined in codebase_rag/cli.py exposes the export command for straightforward extraction.
codebase-rag export -o /tmp/myrepo-graph.json
This command connects to the configured Memgraph instance, invokes the full export pipeline, and writes the results to the specified path. You will see a confirmation message displaying node and relationship counts:
Graph exported successfully to: /tmp/myrepo-graph.json
Exported graph contains 12,384 nodes and 23,571 relationships.
The CLI enforces JSON output and rejects non-JSON formats. If you attempt to use --no-json, the command raises an error because the export system only supports JSON serialization.
Programmatic Export in Python
For integration into larger workflows or custom automation scripts, call the same underlying functions directly without invoking the CLI.
from pathlib import Path
from codebase_rag.services.graph_service import MemgraphIngestor
from codebase_rag.main import export_graph_to_file, connect_memgraph
from codebase_rag import settings
def export_to_json(output_path: str) -> bool:
# Resolve batch size according to settings (same logic the CLI uses)
batch = settings.resolve_batch_size(None)
with connect_memgraph(batch) as ingestor:
return export_graph_to_file(ingestor, output_path)
if __name__ == "__main__":
success = export_to_json("myrepo-graph.json")
print("Export succeeded:", success)
This approach uses export_graph_to_file() from codebase_rag/main.py, which internally calls _write_graph_json() and export_graph_to_dict(), guaranteeing identical output to the CLI command while allowing you to handle errors and paths programmatically.
Loading and Analyzing the Exported Knowledge Graph
Once exported, the JSON file follows the schema defined in codec/schema_pb2.py and can be consumed by the GraphLoader utility in codebase_rag/graph_loader.py.
To inspect the exported data in Python:
from codebase_rag.graph_loader import load_graph
loader = load_graph("myrepo-graph.json")
summary = loader.summary()
print("Nodes:", summary["total_nodes"])
print("Relationships:", summary["total_relationships"])
print("Exported at:", summary["metadata"]["exported_at"])
# Example: list all functions
functions = loader.find_nodes_by_label("Function")
for fn in functions[:5]:
print(" •", fn.properties["qualified_name"])
This mirrors the example script shipped with the repository at examples/graph_export_example.py.
For external analysis in other languages, the pure JSON format requires no special parsers. Here is a Node.js example:
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('myrepo-graph.json', 'utf8'));
console.log(`Graph has ${data.nodes.length} nodes and ${data.relationships.length} relationships`);
console.log('First 3 function nodes:');
data.nodes
.filter(n => n.labels.includes('Function'))
.slice(0, 3)
.forEach(fn => console.log(fn.properties.qualified_name));
Export Format and Schema Structure
The resulting JSON document contains three top-level keys: nodes, relationships, and metadata.
- The
metadataobject includestotal_nodes,total_relationships, and the ISO-8601exported_attimestamp - Each node contains
id,labels, andpropertiesfields - Each relationship contains
id,type,start_node_id,end_node_id, andproperties
The serialization preserves Unicode characters (ensure_ascii=False) and uses consistent indentation for readability. The schema is derived from the protocol buffer definitions in codec/schema_pb2.py, making it straightforward to generate matching data structures in other programming languages.
Summary
- Run
codebase-rag export -o <file.json>to extract the complete graph via CLI - Call
export_graph_to_file()fromcodebase_rag/main.pyfor programmatic Python export - Use
GraphLoaderfromcodebase_rag/graph_loader.pyto reload exported JSON files for analysis - Expect a JSON structure with
nodes,relationships, andmetadatakeys following the schema incodec/schema_pb2.py - Rely on read-only Cypher queries (
CYPHER_EXPORT_NODESandCYPHER_EXPORT_RELATIONSHIPS) executed byMemgraphIngestor.export_graph_to_dict()incodebase_rag/services/graph_service.py
Frequently Asked Questions
What format does the exported knowledge graph use?
The export produces a single JSON file containing the complete graph structure. The format includes three top-level keys: nodes (array of node objects), relationships (array of relationship objects), and metadata (object with counts and timestamps). This schema is defined in codec/schema_pb2.py and uses Unicode-safe encoding with human-readable indentation.
Can I export the graph without using the CLI?
Yes. Import export_graph_to_file from codebase_rag/main.py and call it with a configured MemgraphIngestor instance. You can obtain the ingestor by calling connect_memgraph() with an appropriate batch size resolved from settings.resolve_batch_size(). This programmatic approach is identical to the CLI implementation.
How do I load an exported graph back into Python?
Use the load_graph() function from codebase_rag/graph_loader.py. This utility reconstructs the node and relationship objects, provides fast lookups by label or ID via find_nodes_by_label(), and offers a summary() method to inspect metadata without parsing JSON manually.
Is the export process read-only and safe for production databases?
Yes. The export process executes only read-only Cypher queries (CYPHER_EXPORT_NODES and CYPHER_EXPORT_RELATIONSHIPS) through the export_graph_to_dict() method in MemgraphIngestor. It does not modify any existing data, making it safe to run against production Memgraph instances during active operations.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →