Zero Labs
Industry News / AI

Building a Production-Ready RAG System with Incremental Indexing

Source · Towards AI By Aayush Gupta

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

A comprehensive guide to building a Retrieval-Augmented Generation (RAG) system that efficiently manages document updates, deletions, and additions without re-indexing everything.Source: GeminiIntroductionRetrieval-Augmented Generation (RAG) has become the go-to architecture for building AI applications that need to answer questions based on custom knowledge bases. However, most RAG tutorials skip over a critical production concern: how do you efficiently update your knowledge base without re-indexing everything?In this article, I’ll walk you through building a RAG system that solves this problem using incremental indexing with SQLRecordManager, allowing you to:Add new documents without re-processing existing onesUpdate changed documents automaticallyRemove deleted documents from the vector storeTrack which documents have been processedWhat is RAG?RAG combines two powerful concepts:Retrieval: Finding relevant information from a knowledge baseGeneration: Using an LLM to generate answers based on that informationThe basic flow is:User Question → Find Relevant Docs → Pass to LLM → Generate AnswerThis approach gives LLMs access to current, domain-specific information without expensive fine-tuning.The Problem with Traditional RAGMost RAG implementations have a critical flaw in their document management:# Traditional approach - INEFFICIENTdef update_database(): # Delete everything vector_store.delete_collection() # Re-load ALL documents docs = load_all_documents() # Re-chunk ALL documents chunks = split_documents(docs) # Re-embed and re-index EVERYTHING vector_store.add_documents(chunks)Problems with this approach:Wastes time re-processing unchanged documentsWastes API calls re-generating embeddingsDoesn’t detect deleted filesBecomes slower as your knowledge base growsNot suitable for production environmentsOur Solution: Incremental IndexingInstead of the “delete everything and start over” approach, we use incremental indexing:# Our approach - EFFICIENTdef sync_folder(): # Load current documents docs = load_documents() # Let the record manager handle the magic stats = index( docs, record_manager, # Tracks what's been indexed vectorstore, cleanup="full", # Removes deleted files source_id_key="source" ) # Only changed documents are processed!Benefits:✅ Only processes new or changed files✅ Automatically removes deleted files✅ Skips unchanged files entirely✅ Scales efficiently with large knowledge bases✅ Production-readyArchitecture OverviewOur RAG system consists of three main components:1. Vector Store (Chroma)Stores document embeddings for similarity searchDocuments → Chunks → Embeddings → Vector Store2. Record Manager (SQLite)Acts as a “ledger” tracking what’s been indexedFile Path → Hash → Timestamp → Status3. LLM (Llama 3.1)Generates answers based on retrieved contextQuestion + Context → LLM → AnswerImplementationProject StructureRAG/├── database.py # Vector store and indexing logic├── rag.py # Query processing and LLM interaction├── main.py # Entry point├── Knowledge/ # Your documents folder│ ├── docker.txt│ └── kubernetes.txt├── chroma_db/ # Vector store (auto-created)└── record_manager_cache.sql # Indexing ledger (auto-created)Core Configuration# Configuration constantsCHROMA_PATH = "chroma_db"RECORD_DB_PATH = "sqlite:///record_manager_cache.sql"SOURCE_FOLDER = "./Knowledge"EMBEDDING_MODEL = "nomic-embed-text"COLLECTION_NAME = "my_rag_collection"CHUNK_SIZE = 600CHUNK_OVERLAP = 100Why these values?Chunk size (600): Balances context completeness with retrieval precisionChunk overlap (100): Ensures important information isn’t split across chunksnomic-embed-text: Fast, efficient embedding model optimized for retrievalDatabase Module (database.py)The database module handles two critical functions:1. Vector Store Initializationdef get_vector_store(): embeddings = OllamaEmbeddings(model=EMBEDDING_MODEL) vectorstore = Chroma( collection_name=COLLECTION_NAME, persist_directory=CHROMA_PATH, embedding_function=embeddings ) return vectorstoreThis creates a persistent vector store that survives between runs.2. Incremental Folder Syncdef sync_folder(): # Initialize components vectorstore = get_vector_store() record_manager = SQLRecordManager( namespace=f"chroma/{COLLECTION_NAME}", db_url=RECORD_DB_PATH ) record_manager.create_schema() # Load and split documents loader = DirectoryLoader(SOURCE_FOLDER, glob="**/*.*", loader_cls=TextLoader) text_splitter = RecursiveCharacterTextSplitter( chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP ) docs = loader.load_and_split(text_splitter) # Incremental indexing - THE MAGIC stats = index( docs, record_manager, vectorstore, cleanup="full", source_id_key="source" ) return statsWhat happens during index()?Hash Calculation: Each document is hashed based on content and metadataComparison: Hashes are compared with the record manager’s ledgerSmart Updates:New files → Added to vector store + ledgerChanged files → Old versions deleted, new versions addedDeleted files → Removed from vector store + ledgerUnchanged files → Skipped entirely (no processing)RAG Module (rag.py)The RAG module handles query processing:def answer_query(question: str): # 1. Initialize db = get_vector_store() llm = ChatOllama(model="llama3.1:8b", temperature=0) # 2. RETRIEVE: Find relevant context results = db.similarity_search(question, k=3) context = "\n\n---\n\n".join([doc.page_content for doc in results]) # 3. GENERATE: Create prompt and get answer prompt = f""" Use the context below to answer the question accurately. Context: {context} Question: {question} """ response = llm.invoke(prompt) return response.content, resultsKey Design Decisions:k=3: Retrieves top 3 most relevant chunks (balances context vs. noise)temperature=0: Ensures deterministic, factual responsesContext separator: --- clearly delineates different source chunksHow It WorksFirst Run1. User adds documents to Knowledge/ folder2. sync_folder() is called3. Documents are loaded and chunked4. Embeddings are generated5. Chunks are stored in Chroma6. Records are saved in SQLite ledgerOutput:Added: 45Updated: 0Deleted: 0Skipped: 0Subsequent Runs (No Changes)1. sync_folder() is called2. Documents are loaded and chunked3. Hashes are compared with ledger4. All hashes match → Nothing to do!Output:Added: 0Updated: 0Deleted: 0Skipped: 45Time saved: ~95% (only loading time, no embedding or indexing)When Files Change1. User modifies docker.txt2. sync_folder() is called3. docker.txt hash doesn't match ledger4. Old docker.txt chunks are deleted5. New docker.txt chunks are added6. Other files are skippedOutput:Added: 8 (new docker.txt chunks)Updated: 0Deleted: 8 (old docker.txt chunks)Skipped: 37 (unchanged files)When Files Are Deleted1. User deletes kubernetes.txt2. sync_folder() is called with cleanup="full"3. System compares ledger with current files4. kubernetes.txt chunks are removed5. Other files are skippedOutput:Added: 0Updated: 0Deleted: 12 (kubernetes.txt chunks)Skipped: 33UsageInstallation# Install dependenciespip install langchain langchain-ollama langchain-chroma langchain-community# Install Ollama# Visit: https://ollama.ai# Pull required modelsollama pull nomic-embed-textollama pull llama3.1:8bBasic Usage# main.pyfrom database import sync_folderfrom rag import answer_query# Sync your knowledge basesync_folder()# Ask questionsanswer, sources = answer_query("What is Docker?")print(answer)Adding Documents# Just add .txt files to Knowledge/ folderecho "Docker is a containerization platform..." > Knowledge/docker.txt# Run syncpython main.py # Only new file will be processedUpdating Documents# Edit existing filenano Knowledge/docker.txt# Run syncpython main.py # Only changed file will be re-processedRemoving Documents# Delete filerm Knowledge/old-doc.txt# Run sync with cleanup="full"python main.py # Deleted file chunks will be removed from vector storePerformance BenefitsLet’s compare traditional vs. incremental indexing:Scenario: 100 documents, modify 1Traditional Approach:Load: 100 documentsChunk: 100 documentsEmbed: 500 chunksIndex: 500 chunksTime: ~5 minutesIncremental Approach:Load: 100 documentsChunk: 100 documentsEmbed: 5 chunks (only changed file)Index: 5 chunks (add new, delete old)Skip: 495 chunksTime: ~15 secondsSavings: 95% time reductionAdvanced FeaturesCustom Chunk Size# For technical documentation (more context needed)CHUNK_SIZE = 1000CHUNK_OVERLAP = 200# For general text (less context needed)CHUNK_SIZE = 400CHUNK_OVERLAP = 50Multiple Knowledge Sources# Load from different foldersloaders = [ DirectoryLoader("./docs", glob="**/*.txt"), DirectoryLoader("./manuals", glob="**/*.md"), DirectoryLoader("./code", glob="**/*.py")]all_docs = []for loader in loaders: all_docs.extend(loader.load())Custom Retrieval# Increase context for complex questionsresults = db.similarity_search(question, k=5)# Use similarity scoresresults_with_scores = db.similarity_search_with_score(question, k=3)for doc, score in results_with_scores: print(f"Relevance: {score}")TroubleshootingDocuments not being indexedCheck file format (must be readable by TextLoader)Verify SOURCE_FOLDER path is correctEnsure files have contentDeletions not detectedMake sure you’re using cleanup="full"Verify record manager is properly initializedCheck that source_id_key matches document metadataOut of memory errorsReduce CHUNK_SIZEProcess documents in batchesUse a vector store with disk persistence (we already use Chroma)ConclusionBuilding a production-ready RAG system requires more than just connecting an LLM to a vector store. Efficient document management through incremental indexing is crucial for:Performance: Only process what’s changedCost: Minimize embedding API callsScalability: Handle growing knowledge basesMaintenance: Easy updates without downtimeThe combination of Chroma for vector storage and SQLRecordManager for tracking changes provides a robust foundation for production RAG applications.Key TakeawaysUse incremental indexing instead of re-indexing everythingTrack document state with a record managerSet cleanup=”full” to detect deleted filesChoose appropriate chunk sizes for your use caseMonitor statistics to understand system behaviorNext StepsAdd support for more file types (PDF, DOCX, HTML)Implement batch processing for large knowledge basesAdd caching for frequently asked questionsSet up monitoring and loggingDeploy with a web interfaceResourcesLangChain DocumentationChroma Vector StoreOllama ModelsBuilding a Production-Ready RAG System with Incremental Indexing was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.