The RAG Architecture: Indexing and Retrieval
Map out the two phases of RAG: the offline indexing phase that chunks, embeds, and stores documents, and the online retrieval phase that finds relevant context for each query.
The RAG Architecture: Indexing and Retrieval is a free AI Engineering Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Engineering Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
RAG Has Two Distinct Phases
A RAG system operates in two fundamentally different phases that run at different times. The offline indexing phase processes your documents once (or when they change) and prepares a searchable index. The online retrieval phase runs in real time for every user query. Understanding this split is essential for designing systems that are both fast at query time and maintainable over time.
The Indexing Phase: Step One — Load
Indexing starts with document loading: reading raw files from your source systems. Documents can be PDFs, Word files, HTML pages, Markdown files, database rows, or any text source. Each document is loaded into memory as plain text, preserving structure where possible. Libraries like pypdf, python-docx, and unstructured handle the heavy lifting of format-specific parsing.
from pypdf import PdfReader
def load_pdf(path):
reader = PdfReader(path)
pages = []
for i, page in enumerate(reader.pages):
text = page.extract_text()
pages.append({'text': text, 'page': i + 1, 'source': path})
return pages
docs = load_pdf('company_policy.pdf')
print(f'Loaded {len(docs)} pages')The Indexing Phase: Step Two — Chunk
LLMs have finite context windows and retrieving entire documents is wasteful. The loaded text is split into smaller chunks of roughly 200-1000 tokens each. Good chunking preserves semantic coherence: a chunk should express a complete idea. A common strategy uses overlapping windows so that sentences near chunk boundaries appear in two chunks, preventing information loss at split points.
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=500, # characters per chunk
chunk_overlap=50, # overlap between chunks
separators=['\n\n', '\n', '. ', ' ']
)
for page in docs:
chunks = splitter.split_text(page['text'])
for chunk in chunks:
# Each chunk carries metadata from its source page
print(f'Chunk ({len(chunk)} chars): {chunk[:80]}...')The Indexing Phase: Step Three — Embed
Each text chunk is converted to a dense vector embedding that captures its semantic meaning numerically. You call an embedding model — such as OpenAI's text-embedding-3-small — for each chunk and receive a high-dimensional float array. Chunks with similar meaning produce vectors that are close in this high-dimensional space, which is what enables semantic similarity search.
from openai import OpenAI
client = OpenAI()
def embed_chunks(chunks):
texts = [c['text'] for c in chunks]
response = client.embeddings.create(
model='text-embedding-3-small',
input=texts
)
for i, chunk in enumerate(chunks):
chunk['embedding'] = response.data[i].embedding
return chunks
# Batch up to 2048 texts per API call
embedded = embed_chunks(all_chunks)The Indexing Phase: Step Four — Store
The embedded chunks are stored in a vector database alongside their metadata (source file, page number, section title). The vector store builds an index structure (typically HNSW) that enables fast approximate nearest neighbor search. This index is persisted to disk so it survives restarts. Indexing typically happens once at setup and incrementally when new documents are added.
import pinecone
pc = pinecone.Pinecone(api_key='YOUR_KEY')
index = pc.Index('rag-documents')
# Upsert vectors with metadata
vectors_to_upsert = [
(
chunk['id'],
chunk['embedding'],
{'text': chunk['text'], 'source': chunk['source'], 'page': chunk['page']}
)
for chunk in embedded_chunks
]
# Upsert in batches of 100
for i in range(0, len(vectors_to_upsert), 100):
index.upsert(vectors=vectors_to_upsert[i:i+100])
print('Indexing complete')The Retrieval Phase: Query Embedding
When a user submits a query, the online retrieval phase begins. The first step is to embed the user's question using the same embedding model used during indexing. This is critical: if you indexed with text-embedding-3-small, you must query with text-embedding-3-small too. The query embedding is a vector that encodes the semantic meaning of what the user is asking.
def embed_query(question):
response = client.embeddings.create(
model='text-embedding-3-small', # MUST match indexing model
input=[question]
)
return response.data[0].embedding
user_question = 'What is our parental leave policy?'
query_vector = embed_query(user_question)
print(f'Query embedded: {len(query_vector)}-dim vector')The Retrieval Phase: ANN Search
The query embedding is sent to the vector store, which performs an approximate nearest neighbor (ANN) search to find the K chunks whose embeddings are most similar to the query vector. This search is extremely fast (typically sub-10ms) because HNSW indexes trade a small amount of recall for massive speed gains over brute-force search. You retrieve the top-K chunks — commonly K=5 to K=20.
results = index.query(
vector=query_vector,
top_k=5,
include_metadata=True
)
print(f'Retrieved {len(results.matches)} chunks:')
for match in results.matches:
print(f' Score: {match.score:.3f} | Source: {match.metadata["source"]}')
print(f' Text: {match.metadata["text"][:100]}...')
print()Connecting the Two Phases
The key insight is that indexing and retrieval are designed to work together. The embedding model must be identical in both phases, because the mathematical space where vectors live is model-specific. If you switch embedding models, you must re-index all documents. The vector store is the bridge: it accepts vectors during indexing and returns vectors during retrieval, decoupling the two phases in time while keeping them aligned in vector space.
Metadata Filtering During Retrieval
Vector search finds semantically similar chunks, but sometimes you also need to filter by metadata. For example: only retrieve chunks from documents uploaded in 2025, or only from the HR department folder. Vector stores support pre-filtering or post-filtering on metadata fields. Pre-filtering (supported by Pinecone and Qdrant) applies the filter before ANN search, which is faster and more accurate than post-filtering on the top-K results.
# Retrieve only from HR department documents
results = index.query(
vector=query_vector,
top_k=5,
filter={'department': {'$eq': 'HR'}},
include_metadata=True
)
# Or filter by date range
results = index.query(
vector=query_vector,
top_k=5,
filter={
'upload_year': {'$gte': 2024},
'doc_type': {'$eq': 'policy'}
},
include_metadata=True
)Incremental Indexing for Updates
In production, your document corpus changes over time. An effective indexing architecture supports incremental updates: when a document is edited, delete its existing vectors by ID and upsert the new ones. When documents are deleted, remove their vectors. Assign each chunk a deterministic ID based on the source document path and chunk position so you can always find and update the right vectors without re-indexing everything.
import hashlib
def make_chunk_id(source_path, chunk_index):
# Deterministic, stable ID for each chunk
key = f'{source_path}::chunk_{chunk_index}'
return hashlib.md5(key.encode()).hexdigest()
def update_document(source_path, index):
# Delete old vectors for this document
index.delete(filter={'source': source_path})
# Re-index the updated document
new_chunks = load_and_chunk(source_path)
new_embedded = embed_chunks(new_chunks)
index.upsert(vectors=new_embedded)
print(f'Updated {source_path}: {len(new_chunks)} chunks')Full RAG Pipeline at a Glance
The complete RAG architecture looks like this: Offline: Documents → Loader → Chunker → Embedding Model → Vector Store. Online: User Query → Embedding Model → Vector Store (ANN search) → Top-K Chunks → Prompt Assembly → LLM → Answer. The offline pipeline runs once per document update. The online pipeline runs in milliseconds for every user query, with the LLM seeing only the relevant context, not the entire document corpus.
Quick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
In this lesson you learned: the offline indexing phase consisting of load, chunk, embed, and store steps that run once per document, the online retrieval phase that embeds the query, performs ANN search, and returns top-K chunks in milliseconds, and incremental indexing strategies for keeping the vector store up to date as documents change. Next up we explore how to craft effective augmented prompts that use retrieved context well.
Frequently asked questions
Is the “The RAG Architecture: Indexing and Retrieval” lesson free?
Yes — the full text of “The RAG Architecture: Indexing and Retrieval” is free to read here on the web, and the AI Engineering Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Engineering Academy course, upgrade to CoddyKit PRO.
What will I learn in “The RAG Architecture: Indexing and Retrieval”?
Map out the two phases of RAG: the offline indexing phase that chunks, embeds, and stores documents, and the online retrieval phase that finds relevant context for each query. You practise AI Engineering Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Engineering Academy?
No prior experience is required. AI Engineering Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The RAG Architecture: Indexing and Retrieval” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Engineering Academy lesson?
Yes. Every AI Engineering Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Problem RAG Solves
- The RAG Architecture: Indexing and Retrieval
- Crafting the Augmented Prompt
- RAG vs Fine-Tuning: When to Use Which