Zero Labs
Industry News / AI

You Don’t Need a Vector DB for Your RAG System — Applied AI #2

Source · Towards AI By Akshay Raman

From the publisher’s feed, collected in the ZeroLabs newsroom.

IntroIn my last post on Context Engineering, I wrote about keeping an agent’s context lean & clean. Trimming what you feed the model so it doesn’t get distracted or “rot” on irrelevant information.The example I used was a policy document: long, dense paragraphs on shipping, returns, and warranties, written the way real companies actually write policy docs. Most real-world documents look like this. And that’s a problem for standard RAG.Source: Image by AuthorTypical RAG assumes the answer to a question lives inside a single chunk (i.e.) whatever fits in your chunk size. But in reality, the information you need is often split across sections: some context in one paragraph, the actual answer a few sections later, a caveat somewhere else entirely.So how do humans deal with this? We don’t read documents chunk by chunk. We look at the structure, like the table of contents, the headings to figure out which section is likely relevant, read it, and piece the answer together from there.What if an LLM did the same thing?That’s exactly what Vectorless RAG does. It’s a retrieval approach that mimics how humans navigate a document. It parses the document’s own structure, and knows how to read a table of contents.It’s simple, intuitive, and quick to set up and it might be exactly what your RAG system needs.The IdeaVectorless RAG is a retrieval augmented generation method which uses document structure + LLM reasoning to find and retrieve segments relevant to a user’s query, rather than retrieving chunks by similarity score. It operates the way a human would parse a document for information.There are different ways to implement this. PageIndex builds a full hierarchical tree and has the LLM traverse it top-down, level by level. LlamaIndex’s Document Summary Index builds a summary per document and has the LLM pick the right document before reading it. Simpler approaches just expose a flat table of contents and let the LLM pick a section directly.The retrieval strategies could vary between implementations. But the underlying steps are the same:Segment by structure — Split the document along its natural boundaries: pages, sections, headings. No arbitrary chunk sizes. Every segment carries meaningful information on its own.Index the structure — Build a lightweight representation of those segments that an LLM can reason over. Depending on the implementation this could be a hierarchical tree, a flat table of contents, or per-document summaries. No embeddings involved.LLM Navigation — On receiving a query, the LLM reasons over the index to identify which segments are relevant, reads their full content, and generates an answer.Here it is visualized.Source: Image by AuthorWhy this approach though?Standard vector RAG makes one core assumption: the answer lives in a chunk that is semantically similar to the query. That breaks down fast in practice:Similarity is not relevanceIn structured documents, the real answer is often buried mid-paragraph, split across sections, or tied to context elsewhere in the document. A similar-looking chunk is not the same as the right chunk.Retrieval is one-shot The system picks chunks and hands them to the LLM. There is no mechanism for the LLM to say “I need to check section 5 before I can answer this.” You get what the retriever gives you.Operational overheadEmbeddings, vector stores, chunking pipelines, re-embedding when models or parameters change. More moving parts than most document QA use cases actually need.Vectorless RAG sidesteps all three, and gives you a lighter more intuitive retriever.Let’s build itPageIndex is one of the more popular frameworks for this. But since the goal here is to understand the mechanics, I’ll build a simpler version from scratch.Fair warning: this is a deliberately dumb implementation. The point is to make the mechanics visible, not to build the most optimised version.Full code: https://github.com/akshay-r13/vectorless-rag-exampleStep 1. Building the Document Index TreeWe’re building a customer support agent for ShopNest, a fictional e-commerce store. The agent has 5 policy documents to work with:/data privacy_policy.txt # 240 Lines returns_policy.txt # 220 Lines seller_policy.txt # 190 Lines shipping_policy.txt # 190 Lines warranty_policy.txt # 140 LinesThese documents have clearly defined section structures to keep this walkthrough readable. Real-world documents will be messier.The Index is a tree where each node represents a folder, document or section. Non-leaf nodes carry a short LLM-generated description of the contents. The leaf nodes carry the actual content.Source: Image by AuthorCode:@dataclassclass IndexNode: """Class for creating a single Node for the Vectorless Index Tree. A Node can be a folder / document / document's section""" id: str title: str type: Literal["folder", "document", "document_section"] description: str | None = None content: str | None = None children: list[IndexNode] = field(default_factory=list)VectorlessIndex wraps the root node and builds the tree from a given path.class VectorlessIndex: """Class definition of the tree object holding the doc / folder contents in a structured format.""" root: IndexNode # root node of the tree node_map: dict[str, IndexNode] # a lookup dictionary to get a node using its id in O(1) time. def __init__(self, path: Path): fingerprint = self._compute_fingerprint(path) # Compute fingerprint of current folder contents if CACHE_PATH.exists(): ... # Cache load logic # If no cache, build the doc tree root = self._build_tree(path) with tqdm(total=root.count_nodes(), desc="Building index") as pbar: root.rollup_summaries(on_complete=pbar.update) self.root = root self._build_node_map() ... # Cache write logic def __str__(self): return json.dumps(asdict(self.root), indent=2) @staticmethod def _build_tree(path: Path) -> IndexNode: """Recursive tree builder function which parses through the directory / file to build out the nodes. Finally returns the root node.""" # If node is folder, attach children and build sub-tree for each document if path.is_dir(): children = [] for child_path in sorted(path.rglob("*.txt")): child_node = VectorlessIndex._build_tree(child_path) children.append(child_node) return IndexNode( id=path.stem, title=path.stem, type="folder", children=children ) # If node is document, parse subsections and create sub-tree. else: content = path.read_text() parsed_sections = parse(content) # Parses document into a list of section objects which has section text, header, level, start and end root_children = [] open_stack = [] for i, section in enumerate(parsed_sections): section_end = parsed_sections[i+1].start if i section_text = content[section.start:section_end] while (open_stack and open_stack[-1][1] >= section.level): open_stack.pop() siblings_list_ref = root_children if not open_stack else open_stack[-1][0].children section_id = f"{path.stem}/{len(root_children)+1}" if not open_stack else f"{path.stem}/{open_stack[-1][0].id.split('/')[-1]}.{len(open_stack[-1][0].children)+1}" section_node = IndexNode( id=section_id, title=path.stem + " / " + section.header, type="document_section", content=section_text ) siblings_list_ref.append(section_node) open_stack.append((section_node, section.level)) root = IndexNode( id=path.stem, title=path.stem, type="document", children=root_children, content=None ) return root def _build_node_map(self) -> None: """Helper funtion to build a hashmap for quick node lookup Populates the `instance.node_map` object""" stack = [self.root] self.node_map = {} while stack: popped_node = stack.pop() self.node_map[popped_node.id] = popped_node stack.extend(popped_node.children) @staticmethod def _compute_fingerprint(path: Path) -> str: """Function to compute hash fingerprint from folder contents. Used for caching reference""" hasher = hashlib.sha256() for file_ in sorted(path.rglob("*.txt")): hasher.update(file_.read_bytes()) return hasher.hexdigest()To build this index yourself in your own system, use the following command.$ uv run python run_indexing.py Building index: 19%|███████ | 24/250 [03:20You’ll need to setup VertexAI credentials first.Step 2: Create Agent Tools for Parsing the Index TreeThe agent needs exactly 2 tools — one to navigate, and one to read:@tooldef list_nodes(node_id: Optional[str]) -> List[dict]: """Use this to explore available documents and sections. Use node_id None or "root" to list all top-level documents. Pass a node_id to drill into its subsections.""" if not node_id or node_id == "root": return [ {"id": c.id, "description": c.description, "children_ids": [child.id for child in c.children]} for c in index.root.children ] return [ {"id": c.id, "description": c.description, "children_ids": [child.id for child in c.children]} for c in index.node_map[node_id].children ]@tooldef read_node(node_id: str) -> str: """Use this to read content of node with given node_id""" return index.node_map[node_id].contentOnly leaf nodes have content. Non-leaf nodes have descriptions only, which nudges the agent to scan the structure before committing to a full read.Step 3: Wiring the AgentThis is the simplest step, we connect the index, tools, system prompt and model together in a langchain agent.This is what our agent.py looks like"""ShopNest customer support agent.Uses a VectorlessIndex to answer customer queries on different policies such as seller, warranty, returns, privacy etc. without using a vector database"""from pathlib import Pathfrom typing import Optional, Listfrom langchain_core.tools import toolfrom langchain_google_genai.chat_models import ChatGoogleGenerativeAIfrom langchain.agents import create_agentfrom vectorless.index import VectorlessIndexindex = VectorlessIndex(Path("./data"))# Create Agent Tools@tooldef list_nodes(node_id: Optional[str]) -> List[dict]: """Use this to explore available documents and sections. Use node_id None or "root" to list all top-level documents. Pass a node_id to drill into its subsections.""" ...@tooldef read_node(node_id: str) -> str: """Use this to read content of node with given node_id""" ...# Initiate Chat Modelmodel = ChatGoogleGenerativeAI( model = "gemini-2.5-flash", temperature = 0, vertexai=True)# Set System PromptSYSTEM_PROMPT = """You are a customer support policy assistant for ShopNest, an e-commerce store.You help customers with queries related to policies such as1. Privacy policy2. Returns policy3. Seller policy4. Shipping policy5. Warranty policyYou have access to a parseable tree document object where each node looks like:Node: id: str title: str type: Literal["folder", "document", "document_section"] description: str content: str children: list[Node]You can parse through the Document tree using the following 2 tools in a chain1. list_nodes2. read_nodeNavigation rule: each node returned by list_nodes includes a children_ids field. If children_ids is non-empty, the node is not a leaf — call list_nodes on it to go deeper. Only call read_node on nodes where children_ids is empty.Do not answer questions unrelated to what is available in the documents"""# Initiate Agentagent = create_agent( model = model, tools = [list_nodes, read_node], system_prompt=SYSTEM_PROMPT)# Convo loopmessages = []while True: user_input = input("You: ").strip() if user_input.lower() == "quit": print("Ending Convo....") break messages.append({"role": "user", "content": user_input}) response = agent.invoke({"messages": messages}) messages = response["messages"] usage = messages[-1].usage_metadata response_content = messages[-1].content if isinstance(response_content, list): response_content = response_content[0]['text'] print(f"\nAssistant: {response_content}\n")Step 4: Test RunUse the following command to converse with the agent:$ uv run python agent.py Building index: 100%|███████████████████████| 250/250 [12:40You: Hey how can u help me?Assistant: I can help you with questions related to ShopNest's policies, including:* Privacy policy* Returns policy* Seller policy* Shipping policy* Warranty policyWhat can I help you with today?You: Let us fire few example questions to see how well it performsExample #1 : Navigating by reasoning, not keywordsLet’s start simple. A single document lookup, but with a twist. I ask for shipping times to LA. Not Los Angeles. Not California. Just “LA.” The policy document only mentions California.>> Calling: list_nodes | Input: {'node_id': 'root'}>> Done: [{"id": "privacy_policy", ...}, {"id": "shipping_policy", ...}, ...]>> Calling: list_nodes | Input: {'node_id': 'shipping_policy'}>> Done: [{"id": "shipping_policy/1", ...}, {"id": "shipping_policy/2", ...}, ...]>> Calling: list_nodes | Input: {'node_id': 'shipping_policy/2'}>> Done: [{"id": "shipping_policy/2.1", "description": "Regional delivery timelines...", ...}, ...]>> Calling: list_nodes | Input: {'node_id': 'shipping_policy/2.1'}>> Done: [{"id": "shipping_policy/2.1.1", ...}, ..., {"id": "shipping_policy/2.1.4", ...}]>> Calling: read_node | Input: {'node_id': 'shipping_policy/2.1.4'}>> Done: '2.1.4 Western United States — California, Oregon, Washington, Nevada, Arizona: 4–7 business days.'Assistant: For Los Angeles, which is in California, the usual shipping time is 4–7 business days.Watch the traversal — 4 list_nodes calls before a single read_node. It was scanning, reading the descriptions at each level, picked the right branch, and only read content once it hit a leaf.And it connected “LA” → “Los Angeles” → “California” → “Western United States” entirely on its own.That’s exactly how you’d navigate this document yourself.Example # 2: Multi-section retrieval within a documentYou: I ordered a pair of earphones last week but I do not like them anymore. Can you help me with the process of returning them as well as how long it will take to get my money back?>> Calling: list_nodes | Input: {'node_id': None}>> Done: [{"id": "privacy_policy", ...}, {"id": "returns_policy", ...}, ...]>> Calling: list_nodes | Input: {'node_id': 'returns_policy'}>> Done: [{"id": "returns_policy/1", ...}, {"id": "returns_policy/3", ...}, ...]>> Calling: read_node | Input: {'node_id': 'returns_policy/1'} → null, drilling deeper>> Calling: list_nodes | Input: {'node_id': 'returns_policy/1'}>> Calling: read_node | Input: {'node_id': 'returns_policy/1.1'} → null, drilling deeper>> Calling: list_nodes | Input: {'node_id': 'returns_policy/1.1'}>> Calling: read_node | Input: {'node_id': 'returns_policy/1.1.1'}>> Done: '1.1.1 Standard Item Returns — 30-day return window from delivery date...'>> Calling: list_nodes | Input: {'node_id': 'returns_policy/3'}>> Calling: read_node | Input: {'node_id': 'returns_policy/3.1'} → null, drilling deeper>> Calling: list_nodes | Input: {'node_id': 'returns_policy/3.1'}>> Calling: read_node | Input: {'node_id': 'returns_policy/3.1.1'}>> Done: '3.1.1 Credit and Debit Card Refunds — processed within 3–5 business days...'>> Calling: read_node | Input: {'node_id': 'returns_policy/3.2.1'}>> Done: '3.2.1 Standard Processing Timeline — full timeline 7–14 business days...'Assistant: To return your earphones, please note the following:You have a 30-day return window from the date the carrier marked your order as delivered. The earphones must be in the same condition as you received them. If they came with a security seal, that seal must be intact for the return to be accepted.Regarding your refund:Once ShopNest receives and inspects the returned item, you will get an email notification confirming if your return has been approved or rejected. If approved, the refund is processed within 3-5 business days of the inspection date.The full timeline from when ShopNest receives your return until the funds appear in your account is typically 7-14 business days. For credit and debit card refunds, while ShopNest processes them within 3-5 business days, your bank or card issuer might take an additional 3-7 business days for the credit to show on your statement. ShopNest does not control these bank processing times.This one needed two things: the return process and the refund timeline. Those live in completely different sections of the returns policy. Watch the traversal: the agent navigated to Section 1 first (return eligibility), read the relevant leaf, then jumped across to Section 3 (refund processing timelines) and drilled down there separately.That’s the retrieval pattern vector RAG can struggle with when the answer isn’t in one place.Example #3: Cross-document retrievalHere I try an example where the agent has to look at seller policy as well as returns policy to answer me. The traversal is quite extensive by the agent.You: I'm planning to sell electronics on ShopNest. What are the fees involved and what's the return policy my customers would experience?>> Calling: list_nodes | Input: {'node_id': None}>> Done: [..., {"id": "seller_policy", ...}, {"id": "returns_policy", ...}, ...]# ── seller_policy ──────────────────────────────────────────────────────────────>> Calling: list_nodes | Input: {'node_id': 'seller_policy'}>> Done: [..., {"id": "seller_policy/3", "description": "Fees and payment schedules...", ...}, ...]>> Calling: list_nodes | Input: {'node_id': 'seller_policy/3'}>> Done: [{"id": "seller_policy/3.1", "description": "Referral fees by category...", ...}, ...]>> Calling: read_node | Input: {'node_id': 'seller_policy/3.1'} → null, drilling deeper>> Calling: list_nodes | Input: {'node_id': 'seller_policy/3.1'}>> Done: [{"id": "seller_policy/3.1.1", "children_ids": []}, {"id": "seller_policy/3.1.2", "children_ids": []}, {"id": "seller_policy/3.1.3", "children_ids": []}]>> Calling: read_node | Input: {'node_id': 'seller_policy/3.1.1'}>> Done: '3.1.1 Standard Referral Fees — Consumer Electronics: 8%, Computers: 8%, ...'>> Calling: read_node | Input: {'node_id': 'seller_policy/3.1.2'}>> Done: '3.1.2 Minimum Referral Fee — $0.50 per item across all categories...'>> Calling: read_node | Input: {'node_id': 'seller_policy/3.1.3'}>> Done: '3.1.3 Additional Fees — SNF fee, $39.99/month Pro subscription, ad fees...'# ── returns_policy ─────────────────────────────────────────────────────────────>> Calling: list_nodes | Input: {'node_id': 'returns_policy'}>> Done: [{"id": "returns_policy/1", "description": "Return windows and rules...", ...}, {"id": "returns_policy/2", "description": "Return shipping...", ...}, ...]>> Calling: list_nodes | Input: {'node_id': 'returns_policy/1'}>> Calling: read_node | Input: {'node_id': 'returns_policy/1.1'} → null, drilling deeper>> Calling: list_nodes | Input: {'node_id': 'returns_policy/1.1'}>> Calling: read_node | Input: {'node_id': 'returns_policy/1.1.1'}>> Done: '1.1.1 Standard Item Returns — 30-day window, original condition required...'>> Calling: read_node | Input: {'node_id': 'returns_policy/1.1.2'}>> Done: '1.1.2 High-Value Items — photo verification >$500, in-person inspection >$1000...'>> Calling: read_node | Input: {'node_id': 'returns_policy/2.1.1'}>> Done: '2.1.1 Return Reasons — ShopNest error: prepaid label. Change of mind: customer pays...'>> Calling: read_node | Input: {'node_id': 'returns_policy/3.2.1'}>> Done: '3.2.1 Standard Processing Timeline — approved refunds processed in 7–14 business days...'Assistant: Here's a summary of the fees involved in selling electronics on ShopNest and the return policy your customers would experience:**Seller Fees for Electronics:*** **Standard Referral Fees:** For Consumer Electronics and Computers & Accessories, the referral fee is 8%. For other categories like Home & Kitchen, Health & Personal Care, Sports & Outdoors, and Toys & Games, it's 10-12%. Books & Media and Clothing, Shoes & Accessories have a 15% fee.* **Minimum Referral Fee:** A minimum referral fee of $0.50 per item applies across all categories. If the percentage-based fee is less than $0.50, the minimum fee will be charged.* **Additional Fees:** .....**Customer Return Policy:****General Return Guidelines:*** **Standard Return Window:** Customers have 30 days from the delivery date to return most general merchandise, including electronics accessories. Items must be in their original condition with security seals intact. ....**Return Shipping:*** **Cost Responsibility:** * **ShopNest Error:** If the return is due to a ShopNest error (wrong item, damaged in transit, not as described), ShopNest will issue a prepaid return label, and the customer is not responsible for shipping costs. ....**Refunds:*** **Processing Timelines:** * **Credit/Debit Cards:** Refunds are processed within 3-5 business days of approval, but may take an additional 3-7 business days to appear on the statement depending on the bank. ....The agent pulled the electronics referral fee (8%) and additional fee structure from seller_policy, then switched to returns_policy to cover the 30-day return window, the high-value item verification rules, and what happens with defective products. Two documents, one coherent answer.When should you actually use Vectorless RAG?Consider this approach based on the following conditions:Your documents have natural structure — sections, sub-sections, headers. Policies, manuals, wikis, SOPs. If the content already has a hierarchy, the index just makes it navigable.Your corpus is bounded. This works great across a couple hundred documents. At ten thousand, you want a vector DB.Your queries need reasoning, not just retrieval. Vector search finds chunks that look like the question. This approach lets the agent follow a thread, combine facts across sections, and figure out what is relevant on its own.If your documents are unstructured blobs of text, or you’re working at scale, reach for a vector DB. But if your problem fits the criteria above, you’re adding complexity you don’t need.And that’s really itI hope this article made the case that you don’t always need a vector DB, and more importantly, showed you a concrete alternative method you can use in your own projects.Here’s all the code for this article — https://github.com/akshay-r13/vectorless-rag-exampleCheers!Source: Image by AuthorYou Don’t Need a Vector DB for Your RAG System — Applied AI #2 was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.