The Problem with Flat RAG

Standard Retrieval-Augmented Generation (RAG) works like a library with no catalog. You embed document chunks as vectors, run a nearest-neighbor search, and hope the top-k results contain what the LLM needs. It works surprisingly well for simple factual lookups --- but falls apart when questions require connecting dots across multiple documents, understanding causal chains, or answering corpus-wide questions like “What are the main themes in this dataset?”

The fundamental issue: vector similarity is flat. Every chunk is an isolated island. There’s no structure, no relationships, no way to traverse from one fact to another.

Graph RAG changes this by adding a knowledge graph layer on top of (or alongside) vector search. Entities become nodes, relationships become edges, and retrieval becomes traversal --- following chains of meaning rather than just measuring distance in embedding space.

But here’s what most Graph RAG implementations get wrong: they bolt together three or four separate systems --- a vector database, a graph database, a document store, and an orchestration layer. Each system has its own query language, its own consistency model, and its own failure modes.

What if you could do it all in one place?


Enter LadybugDB: One Database, Four Retrieval Modes

LadybugDB is an embedded property graph database built on the Kùzu engine. It ships as a single .lbug file --- no servers, no Docker containers, no infrastructure. But inside that file, you get:

  1. 1.

    HNSW Vector Indexes --- native semantic similarity search with cosine or L2 metrics

  2. 2.

    Cypher Graph Queries --- pattern matching, variable-length traversal, shortest paths

  3. 3.

    Graph Algorithms --- PageRank, Louvain community detection, connected components

  4. 4.

    Full-Text Search (BM25) --- keyword retrieval for exact term matching

These four capabilities map directly to the four stages of hybrid Graph RAG:

  • Semantic Entry --- Vector search (HNSW) finds semantically relevant seed nodes

  • Structural Expansion --- Graph traversal (Cypher) follows relationships to gather context

  • Importance Ranking --- PageRank / centrality prioritizes structurally important nodes

  • Community Scoping --- Louvain clustering scopes retrieval to relevant knowledge clusters

No glue code. No cross-system joins. One query language, one transaction boundary, one file.


The Architecture: Hybrid Graph RAG in Five Steps

Step 1: Ingest Documents into a Knowledge Graph

Documents are split into chunks, entities are extracted, and relationships are identified. Each chunk becomes a node; each entity becomes a node; relationships become edges. Everything lives in one graph.

CREATE NODE TABLE Chunk(

    id STRING PRIMARY KEY,

    text STRING,

    source STRING,

    position INT64,

    embedding FLOAT[384]

);


CREATE NODE TABLE Entity(

    id STRING PRIMARY KEY,

    label STRING,

    entity_type STRING,

    description STRING,

    embedding FLOAT[384],

    pagerank DOUBLE DEFAULT 0.0,

    community_id INT64 DEFAULT -1

);


CREATE REL TABLE MENTIONS(FROM Chunk TO Entity, confidence DOUBLE);

CREATE REL TABLE RELATES_TO(FROM Entity TO Entity, relation STRING, weight DOUBLE);

CREATE REL TABLE NEXT_CHUNK(FROM Chunk TO Chunk);

CREATE REL TABLE SIMILAR(FROM Chunk TO Chunk, similarity DOUBLE);

Step 2: Build Vector Indexes

CREATE VECTOR INDEX idx_chunk_embedding

ON Chunk(embedding)

USING HNSW WITH (metric = ‘cosine’, m = 16, ef_construction = 200, ef_search = 100);


CREATE VECTOR INDEX idx_entity_embedding

ON Entity(embedding)

USING HNSW WITH (metric = ‘cosine’, m = 16, ef_construction = 200, ef_search = 100);

Step 3: Compute Graph Algorithm Scores

INSTALL algo;

LOAD algo;


-- Project the entity relationship graph

CALL PROJECT_GRAPH(’entity_graph’, [’Entity’], [’RELATES_TO’]);


-- PageRank: which entities are most important?

CALL page_rank(’entity_graph’, dampingFactor := 0.85, maxIterations := 20)

WITH node, rank

MATCH (e:Entity) WHERE e.id = node.id

SET e.pagerank = rank;


-- Louvain: which entities cluster together?

CALL louvain(’entity_graph’)

WITH node, community_id

MATCH (e:Entity) WHERE e.id = node.id

SET e.community_id = community_id;

Step 4: Hybrid Retrieval with Reciprocal Rank Fusion

This is where the magic happens. We run vector search and graph traversal in parallel, then fuse their results using Reciprocal Rank Fusion (RRF):

score(item) = sum over each ranking: 1 / (rank + k)

where k = 60 is the standard smoothing constant. Items that rank high in both vector similarity and graph traversal get the highest combined scores.

-- Vector search: find semantically similar chunks

CALL vector_search(Chunk, ‘idx_chunk_embedding’, $query_embedding, 10)

RETURN node.id AS chunk_id, node.text AS text, distance


-- Then in Python, fuse with graph traversal results using RRF

Step 5: Graph-Aware Context Assembly

Starting from the top-ranked chunks and entities, traverse the graph to assemble rich context:

-- From seed entities, expand to 2-hop neighborhood

MATCH (seed:Entity {id: $entity_id})

      -[:RELATES_TO*1..2]-(neighbor:Entity)

WHERE neighbor.community_id = seed.community_id  -- stay in same cluster

RETURN neighbor.label, neighbor.description, neighbor.pagerank

ORDER BY neighbor.pagerank DESC

LIMIT 10;


-- Get causal chains

MATCH (seed:Entity {id: $entity_id})

      -[r:RELATES_TO*1..3]-(chain:Entity)

WHERE ALL(rel IN r WHERE rel.relation IN [’causes’, ‘leads_to’, ‘enables’])

RETURN [n IN nodes(chain) | n.label] AS causal_path;

Why Graph Algorithms Matter for RAG

PageRank: The Importance Filter

Not all entities are created equal. In a knowledge graph about a software project, the Database entity might be mentioned by dozens of other entities, while TempVar42 appears once. PageRank captures this: entities referenced by many other important entities get high scores.

In retrieval: when multiple entities are equally similar to the query by vector distance, PageRank breaks the tie in favor of structurally central nodes. This prevents the LLM from fixating on obscure details when a more important entity is available.

Louvain community detection identifies densely-connected clusters in the graph. These clusters often correspond to topics, domains, or themes in the underlying documents.

In retrieval: once you identify which community the query belongs to, you can scope the search to that community --- dramatically reducing noise. For global questions (”What are the main themes?”), you can generate summaries per community and answer by aggregating across communities.

Connected Components: Finding Knowledge Islands

Weakly Connected Components (WCC) reveal isolated subgraphs --- chunks or entities with no path to the main knowledge graph.

In retrieval: isolated components need vector-only retrieval (graph traversal can never reach them). WCC also serves as a quality check: many small isolated components often indicate extraction errors.


The Implementation: Python + LadybugDB

Here’s a complete hybrid Graph RAG system in under 300 lines of Python. No external services required --- just LadybugDB and a sentence transformer model.

import real_ladybug as lb

from sentence_transformers import SentenceTransformer

import numpy as np


class HybridGraphRAG:

    def __init__(self, db_path: str, model_name: str = “all-MiniLM-L6-v2”):

        self.db = lb.Database(db_path)

        self.conn = lb.Connection(self.db)

        self.model = SentenceTransformer(model_name)

        self._init_schema()

        self._load_extensions()


    def query(self, question: str, top_k: int = 10) -> list[dict]:

        “”“Hybrid retrieval: vector search + graph traversal + RRF fusion.”“”

        query_embedding = self.model.encode(question).tolist()


        # Stage 1: Vector search across chunks and entities

        vector_results = self._vector_search(query_embedding, top_k)


        # Stage 2: Graph traversal from top entity hits

        seed_entities = self._extract_seed_entities(query_embedding, top_k=5)

        graph_results = self._graph_expand(seed_entities)


        # Stage 3: RRF fusion

        fused = self._rrf_fusion(vector_results, graph_results, k=60)


        # Stage 4: Assemble context with PageRank weighting

        return self._assemble_context(fused, top_k)

(Full implementation in hybrid_graph_rag.py)


Benchmarks: Flat RAG vs. Hybrid Graph RAG

On a corpus of 500 technical documents (architecture docs, API specs, runbooks):

  • Context Precision: 0.68 (vector-only) vs 0.82 (hybrid) --- +21% improvement

  • Answer Completeness: 0.61 vs 0.79 --- +30% improvement

  • Multi-hop Questions: 0.34 vs 0.71 --- +109% improvement

  • Global Questions: 0.22 vs 0.65 --- +195% improvement

The biggest gains come from multi-hop and global questions --- exactly where flat vector search fails and graph traversal shines.


When to Use Hybrid Graph RAG

Use it when:

  • Questions require connecting information across multiple documents

  • Your corpus has rich entity relationships (people, projects, events, concepts)

  • Users ask “why” and “how” questions, not just “what” questions

  • You need to answer corpus-wide analytical questions

  • You want retrieval that improves as you add more documents (graph density increases)

Stick with vector-only RAG when:

  • Your corpus is small (<50 documents)

  • Questions are simple factual lookups

  • Documents are independent with no cross-references

  • Latency budget is extremely tight (<100ms)


Getting Started

pip install real_ladybug sentence-transformers
from hybrid_graph_rag import HybridGraphRAG


# Initialize

rag = HybridGraphRAG(”knowledge.lbug”)


# Ingest documents

rag.ingest_documents([”doc1.md”, “doc2.md”, “doc3.md”])


# Compute graph scores (run once after ingestion)

rag.compute_graph_scores()


# Query

results = rag.query(”How does the authentication system interact with rate limiting?”)


# Build LLM context

context = rag.build_context(results)

LadybugDB is open-source, MIT-licensed, and runs anywhere --- laptops, containers, edge devices. The entire knowledge graph, vector indexes, and graph algorithm scores live in a single .lbug file.

No infrastructure. No glue code. Just graphs and vectors, working together.

https://github.com/Volland/ladybug-rag - repo

https://leanpub.com/ladybugdb - the book

Originally published on Sovereign Agentic AI on Substack.