I’ve been building retrieval systems for a while now, and there’s a moment every RAG developer hits. Your vector search works great on twenty documents. It works fine on two hundred. But somewhere around two thousand, you start noticing something uncomfortable: the answers are getting worse even as you add more data.
More documents should mean better answers. Instead, you get more noise. More near-misses. More chunks that are semantically close to your query but contextually irrelevant. The system retrieves text about the right topic but misses the text that actually answers the question.
I hit that wall hard enough to rethink the entire approach. The result is an open-source Rust implementation of Hybrid Graph RAG, and this article is about what I learned building it.
The full implementation is at github.com/Volland/ladybug-rag-rs. For the deeper theory behind the graph database that powers this approach, see the book LadybugDB -- The Embedded Graph Database on Leanpub.
The Problem with “Find Me Something Similar”
Let’s be concrete. Say you have a technical knowledge base with documents about Rust programming. You ask: “How does ownership ensure memory safety?”
A vector search embeds your query and finds the five most similar chunks. You’ll get paragraphs that mention ownership and memory safety together. That sounds right. But the best answer to this question actually lives across three separate documents: one explains ownership rules, another describes the borrow checker, and a third discusses compile-time guarantees. These chunks don’t use the same words. They’re connected through concepts, not vocabulary.
Vector similarity captures local semantics -- what a chunk of text means in isolation. It doesn’t capture structural relationships -- how pieces of information connect to each other across your corpus. And for any question that requires synthesizing knowledge from multiple sources, that structural understanding is exactly what you need.
This isn’t a theoretical concern. When I benchmarked hybrid retrieval against vector-only on 500 technical documents, the numbers were striking. Context precision improved by 21 percent. Answer completeness went up 30 percent. Multi-hop question accuracy -- the kind of question that requires connecting dots across documents -- improved by 109 percent. And for global questions about overall themes and structure, the improvement was 195 percent.
The gains are largest precisely where traditional RAG struggles most.
What If Your Retrieval System Could Think in Graphs?
The core idea behind Hybrid Graph RAG is deceptively simple: don’t just embed your documents into vectors. Also extract the entities and relationships from your text and build a knowledge graph alongside your vector index. Then, at query time, use both signals together.
When a user asks a question, two things happen in parallel. The vector store finds semantically similar chunks, just like traditional RAG. But simultaneously, the system identifies relevant entities in the query, then walks the knowledge graph outward from those entities, collecting connected chunks along the way. A chunk about the borrow checker might not be semantically similar to a query about ownership, but it’s one hop away in the entity graph -- because both chunks mention “Rust” and “memory safety” as entities.
The magic happens when you fuse these two ranked lists together. A chunk that appears in both the vector results and the graph results -- semantically similar and structurally connected -- gets the highest score. This fusion, called Reciprocal Rank Fusion, is the mechanism that turns two mediocre signals into one strong one.
But walking a knowledge graph naively doesn’t work either. Not all paths are equally valuable. Not all entities are equally important. This is where graph algorithms transform the approach from interesting to powerful.
PageRank: Teaching Your Knowledge Graph What Matters
In a knowledge graph with thousands of entities, most of them are noise. Peripheral mentions, incidental terms, formatting artifacts that your entity extractor picked up. If you treat all graph paths equally during expansion, you’ll follow edges to “The” with the same enthusiasm as edges to “Ownership.”
PageRank solves this elegantly. The same algorithm Google used to rank web pages works beautifully on knowledge graphs. An entity is important if it’s connected to other important entities. It’s a recursive definition that, when computed to convergence, produces an importance score for every node in your graph.
In practice, this means that when the system expands outward from seed entities, it prioritizes paths through high-PageRank nodes. A query about “Rust” will preferentially follow the path through “Ownership” (a core concept with many connections) rather than through “The” (a spurious entity with low structural importance). The damping factor of 0.85 prevents scores from concentrating in tightly connected cliques, ensuring that the algorithm explores broadly while still respecting structure.
The implementation in the Rust codebase is straightforward. After ingesting documents and building the knowledge graph, you compute PageRank once over the entire graph. Then during retrieval, each entity’s PageRank score weights its contribution to the expansion results.
Louvain: Discovering the Topics You Didn’t Know You Had
The second algorithm that makes this work is Louvain community detection. If PageRank tells you which entities matter, Louvain tells you what groups they belong to.
Louvain partitions the knowledge graph into communities -- clusters of densely connected entities that represent emergent topics. You don’t define these topics in advance. They fall out of the graph structure organically. In a technical knowledge base, you might discover that PageRank, BFS, Louvain, and “Graph Databases” form one community, while “Ownership,” “Borrow Checker,” and “Lifetimes” form another.
This has three practical applications in RAG.
First, scoped retrieval. When a query is clearly about graph algorithms, the system can focus its graph expansion on the graph algorithms community rather than wandering into unrelated topics about memory management. This reduces noise dramatically.
Second, global questions. When someone asks “What are the main themes in this knowledge base?”, you can’t answer that with vector search. But you can sample representative entities from each Louvain community and give a structured overview of the topic landscape.
Third, quality diagnostics. A community with many entities and rich internal connections indicates well-documented territory. A community with one or two orphan entities might indicate gaps in your knowledge base. This turns your RAG system into a tool for understanding your corpus, not just searching it.
The Five-Stage Pipeline
The full system operates in five stages, and understanding this pipeline is key to understanding why the approach works.
Stage one is ingestion. Documents are split into chunks using a paragraph-aware splitter that respects natural text boundaries. From each chunk, the system extracts entities -- capitalized noun phrases that represent concepts and terms. When two entities appear in the same sentence, a relationship edge is created between them. This is deliberately simple. You could plug in a more sophisticated NER system or an LLM-based entity extractor, but even regex-based extraction produces surprisingly useful knowledge graphs.
Stage two is indexing. Two parallel data structures are built. A vector index stores chunk embeddings for semantic search. A knowledge graph stores three types of edges: MENTIONS edges connecting chunks to the entities they contain, RELATES_TO edges connecting co-occurring entities, and NEXT_CHUNK edges preserving the sequential order of the original document. This dual indexing is the foundation that makes hybrid retrieval possible.
Stage three is analysis. This is where icebug -- the graph algorithm engine -- does its work. PageRank computes importance scores across all entities. Louvain assigns every entity to a topic community. This is a one-time computation after ingestion, or a periodic recomputation as new documents arrive. It’s fast: PageRank on a 100K-node graph completes in milliseconds thanks to icebug’s OpenMP-parallelized C++ implementation.
Stage four is retrieval. Given a query, two paths run in parallel. Vector search finds the most semantically similar chunks. Graph expansion identifies seed entities, walks the knowledge graph outward for two hops, and collects chunks weighted by the PageRank of the entities that led to them. Reciprocal Rank Fusion merges both ranked lists. The formula is simple but effective: for each chunk, sum one over the quantity (k plus rank) for each list the chunk appears in. Chunks in both lists receive the highest combined scores.
Stage five is assembly. The top-ranked chunks are assembled into an LLM-ready context with source attribution, entity annotations, and neighboring chunks for continuity. A token budget ensures the assembled context respects the LLM’s context window.
Why Rust?
Building a RAG engine might seem like Python territory, and indeed the original prototype was in Python (also open source at github.com/Volland/ladybug-rag). But Rust turned out to be the right choice for the production implementation for several reasons.
The most obvious is performance. The icebug graph algorithm library is written in C++, and Rust’s FFI gives you zero-overhead bindings. There’s no serialization, no copying, no interpreter overhead. When you call PageRank from Rust, you’re calling the C++ function directly. For a system that needs to compute graph algorithms over large knowledge graphs and serve retrieval queries with low latency, this matters.
But the deeper reason is safety. The RAG engine manages complex state -- a vector store, a knowledge graph with bidirectional ID mappings, embedding buffers, graph algorithm results. In Python, it’s easy to hold a stale reference, forget to update a mapping, or introduce a subtle memory leak that only manifests under load. Rust’s ownership system catches these bugs at compile time. The icebug bindings use NonNull pointers and Drop implementations to ensure that every C++ resource is properly cleaned up, even if your code panics.
The architecture is organized as a three-crate Rust workspace. At the bottom, icebug-sys provides raw C FFI declarations -- unsafe, low-level, direct bindings to icebug’s C++ API. Above that, icebug wraps these in safe Rust types: Graph, PageRank, Louvain, and Bfs, each with proper lifetime management. At the top, ladybug-rag is the RAG engine itself, built entirely on safe abstractions.
The embedding layer uses a trait-based design. The Embedder trait defines an interface for turning text into vectors. The included SimpleEmbedder uses character trigram hashing for testing and development. For production, you can swap in the optional OnnxEmbedder, which runs multilingual embedding models locally through ONNX Runtime, or integrate any remote embedding API.
The Counterintuitive Scaling Property
Here’s the thing about vector-only RAG that nobody talks about enough: it gets noisier as your corpus grows. More documents mean more near-miss results competing for the top-k slots. Your signal-to-noise ratio degrades precisely when you need it most.
Graph-enhanced retrieval has the opposite property. More documents create a denser entity graph. More entity connections mean stronger PageRank signals, more meaningful community structure, and richer graph expansion paths. The retrieval quality actually improves with scale.
This is the fundamental reason I believe graph-augmented approaches will become standard for any serious RAG deployment. Not because they’re better on toy examples -- vector search is perfectly fine for small corpora and direct factual lookups. But because the problems with vector-only retrieval compound as your knowledge base grows, while the benefits of graph intelligence compound in the other direction.
When Not to Use This
I want to be honest about the tradeoffs. If your corpus is small -- say, fewer than fifty documents -- the overhead of building and maintaining a knowledge graph isn’t worth it. Vector search will work fine, and the entity graph won’t be dense enough to provide meaningful structural signals.
If your questions are exclusively direct factual lookups -- “What is the API rate limit?” -- you don’t need multi-hop reasoning or community-scoped retrieval. A well-tuned vector search with good chunking will get you there.
And if you need sub-100 millisecond latency on every query, the graph expansion step adds a few milliseconds. It’s fast, but it’s not free.
For everything else -- growing corpora, cross-document questions, entity-rich domains like technical documentation or legal contracts or research papers, users who ask “why” and “how” rather than just “what” -- the hybrid approach is worth the investment.
Try It Yourself
The entire implementation is open source and includes 33 tests covering every component from chunking to entity extraction to RRF fusion to end-to-end RAG queries.
git clone https://github.com/Volland/ladybug-rag-rs.git
cd ladybug-rag-rs
git submodule update --init --recursive
cargo run -p ladybug-rag --example demoThe demo ingests two sample documents, builds a knowledge graph with PageRank and community detection, and runs hybrid queries against it. You’ll see the fusion in action -- chunks that appear in both vector and graph results rising to the top.
For a deeper dive into the graph database concepts behind this approach, the book LadybugDB -- The Embedded Graph Database covers graph modeling, Cypher queries, vector indexing, and algorithm-powered applications in depth. And if you want to explore the algorithms themselves, icebug provides over 200 graph algorithms with OpenMP parallelism and Apache Arrow integration.
LadybugDB: The Engine That Unifies Everything
None of this hybrid approach would work if vectors, graphs, and algorithms lived in separate systems. Imagine running your embeddings in one service, your knowledge graph in another, and your PageRank computations in a third, then trying to fuse the results at query time. The latency alone would kill you. The data synchronization would be a nightmare. And the impedance mismatch between systems would leak abstraction at every boundary.
This is the problem LadybugDB was designed to solve. LadybugDB is an embedded property graph database that ships as a single .lbug file and unifies three retrieval paradigms in one engine: vector indexes, graph queries, and graph algorithms. There’s no network hop between “find semantically similar chunks” and “walk the knowledge graph from those chunks.” It all happens in the same process, on the same data.
The vector layer provides native HNSW indexes with cosine distance. Documents and entities get embedded into high-dimensional vectors and indexed for fast approximate nearest-neighbor search. This is your semantic entry point -- given a query, find what’s close in meaning.
The graph layer stores a full property graph -- nodes with labels, edges with types, properties on both. Your documents, chunks, entities, and their relationships form an interconnected structure that you can query with Cypher. Want all entities mentioned in chunks about Rust, ordered by their importance? That’s a one-line Cypher query. Want to traverse two hops from “Ownership” and find every related concept? Also one line.
But the real differentiator is the algorithm layer. Most graph databases treat algorithms as an afterthought -- export your data, run some external computation, import the results back. LadybugDB integrates graph algorithms directly. PageRank, Louvain, shortest paths, centrality measures -- they all operate on the live graph, in-process, with no data movement. This is what makes it practical to compute PageRank over your entire knowledge graph after every ingestion cycle and use those scores at query time without any additional infrastructure.
The book LadybugDB -- The Embedded Graph Database covers the full picture: graph modeling patterns for knowledge bases, Cypher query design, vector index tuning, and how to compose algorithms into retrieval pipelines. If you’re serious about building graph-augmented applications, it’s the reference I wish I’d had when I started.
icebug: The Algorithm Muscle Behind the Intelligence
If LadybugDB is the unified engine, icebug is the algorithm library that gives it its analytical power. icebug is a fork of NetworKit -- one of the most established graph analysis frameworks in the academic world -- reengineered for columnar storage with Apache Arrow and parallelized with OpenMP for multi-core execution.
The scale of icebug matters here. This isn’t a library with three algorithms duct-taped together. It ships over 200 graph algorithms: centrality measures, community detection, graph partitioning, distance computations, link prediction, graph generators, and more. For Hybrid Graph RAG, we lean on three of them, but the breadth means you can experiment with approaches that most RAG implementations can’t even consider.
PageRank is the workhorse for importance scoring. The implementation converges iteratively with configurable damping (0.85 by default) and tolerance (1e-6), and it runs blazingly fast thanks to OpenMP parallelism. On a knowledge graph with tens of thousands of entities, you get results in single-digit milliseconds. That’s fast enough to recompute after every document ingestion if you want to, not just as a batch job.
Louvain community detection is equally performant. The algorithm works in two alternating phases -- local node moves that maximize modularity gain, then community aggregation into super-nodes -- repeated until convergence. What’s remarkable is that it discovers topic structure that often aligns with human intuition about how a knowledge base is organized, despite having no semantic understanding at all. It works purely on graph topology, and the topics emerge from connection density alone.
BFS -- breadth-first search -- is the simplest of the three but arguably the most critical. It’s the traversal engine that powers graph expansion at query time. Starting from seed entities identified by vector search, BFS walks outward hop by hop, discovering chunks that are structurally connected to the query. The implementation tracks distances, which allows the system to weight closer chunks more heavily than distant ones.
The reason icebug makes this entire approach practical is performance. Graph algorithms on knowledge graphs need to be fast enough to run at query time or at least at ingestion time without becoming a bottleneck. A Python implementation of PageRank on a 100K-node graph might take seconds. icebug does it in milliseconds. That’s the difference between “theoretically interesting” and “actually deployable.”
In the Rust codebase, icebug is accessed through a two-layer binding. The icebug-sys crate provides raw C FFI declarations -- forty functions covering graph lifecycle, mutations, queries, PageRank, Louvain, BFS, and partition operations. The icebug crate wraps these in safe Rust types with proper memory management. When you call PageRank::new(&graph, 0.85, 1e-6) in Rust, you’re getting the full power of icebug’s optimized C++ implementation with Rust’s safety guarantees on top. No garbage collector, no runtime overhead, no unsafe code leaking into your application layer.
This layered approach -- LadybugDB providing the unified model, icebug providing the algorithmic power, and Rust providing the safety and performance -- is what makes Hybrid Graph RAG not just a research idea but a system you can actually build, deploy, and trust.
What’s Next
The current implementation demonstrates the core concept with a clean, well-tested codebase. There are obvious directions to extend it: persistent storage instead of in-memory indexes, incremental graph updates as new documents arrive, LLM-based entity extraction for richer knowledge graphs, and integration with actual LLM inference for the final answer generation step.
But the fundamental insight is already here, working, and measurable: when you combine what’s similar with what’s connected and what’s important, you get retrieval that doesn’t just find matching text. You get retrieval that finds what matters.
If you found this useful, the repo is at github.com/Volland/ladybug-rag-rs and the book is at leanpub.com/ladybugdb. Stars, issues, and PRs are welcome.
Originally published on Sovereign Agentic AI on Substack.