# How to Query the Knowledge Graph with Code-Graph-RAG: A Complete Guide

> Learn to query the knowledge graph with Code-Graph-RAG. This guide walks you through setup and natural language querying, translating questions into Cypher for powerful insights.

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

---

**To query the knowledge graph with Code-Graph-RAG, start the Memgraph daemon with `cgr daemon up`, index your repository using `cgr start --repo-path /path/to/repo --update-graph`, then launch the interactive CLI with `cgr start --repo-path /path/to/repo` to ask natural-language questions that get translated into Cypher queries.**

Code-Graph-RAG is an open-source tool that transforms your codebase into a queryable knowledge graph using Memgraph and Tree-sitter parsing. When you need to query the knowledge graph with Code-Graph-RAG, the system leverages Large Language Models (LLMs) to translate natural language into read-only Cypher queries. This article walks through the exact commands, underlying architecture, and programmatic APIs found in the `vitali87/code-graph-rag` repository.

## Prerequisites

Before querying, ensure you have:

- Memgraph running locally (started via `cgr daemon up`)
- A repository indexed with the `--update-graph` flag
- Python 3.8+ installed for programmatic access

## The Three-Step Query Workflow

The query flow consists of three distinct stages: starting the database daemon, populating the graph with structural data, and executing natural-language queries.

### Start the Memgraph Daemon

First, start the graph database daemon that will persist your codebase's structural information:

```bash
cgr daemon up

```

This command launches Memgraph in the background, creating the target database for your knowledge graph.

### Populate the Knowledge Graph

Next, parse your target repository with Tree-sitter to extract entities (functions, classes, modules) and relationships (calls, imports, data-flow):

```bash
cgr start --repo-path /path/to/repo --update-graph

```

Run this only for the first indexing or after significant code changes. The parser writes nodes and edges directly into Memgraph according to the graph loader logic documented in [`codebase_rag/sdk/graph-loader.md`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/sdk/graph-loader.md).

### Ask Natural-Language Questions

With the daemon running and graph populated, launch the interactive REPL:

```bash
cgr start --repo-path /path/to/repo

```

At the prompt, type questions like:

```

Which functions call `process_data`?

```

The system routes your question to an LLM that generates a Cypher query (e.g., `MATCH (f:Function)-[:CALLS]->(g:Function) WHERE g.name='process_data' RETURN f.name`), executes it against Memgraph, and renders results as a formatted table.

## Under the Hood: Architecture and Implementation

Understanding how Code-Graph-RAG processes queries requires examining three key implementation layers.

### LLM-Driven Cypher Generation

The `CypherGenerator` class in [`codebase_rag/services/llm.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/llm.py) handles the translation from natural language to Cypher. It builds structured prompts, calls the configured LLM provider, cleans the response, and validates the query for safety (ensuring read-only operations, no unbounded paths, and allowed procedures only).

### The Query Tool Implementation

The actual execution layer lives in [`codebase_rag/tools/codebase_query.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/tools/codebase_query.py). The `create_query_tool` function instantiates a `Tool` object wrapping the `query_codebase_knowledge_graph` function. This tool:

- Invokes `CypherGenerator.generate` to produce the Cypher query
- Executes against Memgraph via `QueryProtocol.fetch_all`
- Truncates large result sets to prevent console overflow
- Formats output as rich tables for terminal display

### RAG Orchestration

The CLI wires everything together through `create_rag_orchestrator` in [`codebase_rag/services/llm.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/llm.py). This function builds an agent equipped with the query tool (and auxiliary tools), driving the interaction loop that routes your natural-language input to the appropriate backend functions.

## Code Examples

Beyond the interactive CLI, you can query the knowledge graph programmatically or via shell automation.

### Interactive CLI Queries

The standard workflow combines daemon management with interactive exploration:

```bash

# Keep the database running

cgr daemon up

# Index the codebase (one-time or after changes)

cgr start --repo-path ./my-project --update-graph

# Launch interactive mode

cgr start --repo-path ./my-project

```

Once inside the REPL, ask structural questions like "List all classes that inherit from `BaseModel`" or "Find all functions that import `pandas`".

### Programmatic Python Queries

For custom integrations, import the internal components directly:

```python
from codebase_rag.services.llm import CypherGenerator
from codebase_rag.services import QueryProtocol
from codebase_rag.tools.codebase_query import create_query_tool
import asyncio

# Initialize components (requires running Memgraph instance)

cypher_gen = CypherGenerator(active_projects=None)
ingestor = QueryProtocol()  # Wraps pymgclient for Memgraph communication

query_tool = create_query_tool(ingestor, cypher_gen)

async def ask():
    result = await query_tool.function("How many classes are defined in module `utils`?")
    print(result.summary)  # e.g., "✅ 3 results"

    for row in result.results:
        print(row)

asyncio.run(ask())

```

This approach lets you embed Code-Graph-RAG queries into existing Python applications or data pipelines.

### Shell One-Liners

For automation scripts, pipe questions directly into the CLI:

```bash
cgr start --repo-path ./repo <<EOF
List all classes that inherit from `BaseModel`.
EOF

```

This non-interactive mode returns results immediately, suitable for CI/CD pipelines or batch documentation generation.

## Summary

Querying the knowledge graph with Code-Graph-RAG follows a clear pipeline:

- **Start the daemon** using `cgr daemon up` to launch Memgraph
- **Index your repository** with `cgr start --repo-path /path/to/repo --update-graph` to populate nodes and edges
- **Query interactively** using `cgr start --repo-path /path/to/repo` and typing natural-language questions
- **LLM translation** happens via `CypherGenerator` in [`codebase_rag/services/llm.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/llm.py), ensuring safe, read-only Cypher generation
- **Execution** occurs through `create_query_tool` in [`codebase_rag/tools/codebase_query.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/tools/codebase_query.py), which formats results as rich tables
- **Programmatic access** is available by importing `CypherGenerator`, `QueryProtocol`, and `create_query_tool` directly

## Frequently Asked Questions

### How does Code-Graph-RAG convert natural language to Cypher queries?

The system uses the `CypherGenerator` class located in [`codebase_rag/services/llm.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/llm.py). This component constructs prompts containing your question and schema context, sends them to the configured LLM provider, then validates and cleans the returned Cypher to ensure it contains only read-only operations and allowed graph procedures.

### Is it safe to run arbitrary natural-language queries against the knowledge graph?

Yes. The `CypherGenerator` implements validation checks that reject queries containing write operations, unbounded path traversals, or disallowed procedures. Additionally, the `query_codebase_knowledge_graph` function in [`codebase_rag/tools/codebase_query.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/tools/codebase_query.py) executes queries through a restricted protocol, ensuring your graph data remains immutable during querying.

### Can I query the knowledge graph without using the interactive CLI?

Absolutely. Import the core components from [`codebase_rag/services/llm.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/llm.py) and [`codebase_rag/tools/codebase_query.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/tools/codebase_query.py) to build custom query tools. Initialize `CypherGenerator` and `QueryProtocol`, then pass them to `create_query_tool` to execute queries programmatically from Python scripts or web applications.

### What database does Code-Graph-RAG use to store the knowledge graph?

Code-Graph-RAG uses **Memgraph**, an in-memory graph database. The `cgr daemon up` command starts the Memgraph instance, while `QueryProtocol` (wrapping pymgclient) handles the connection and query execution. All structural data parsed from your repository resides in Memgraph nodes and edges until you stop the daemon.