0Pricing
AI Engineering Academy · Lección

La arquitectura RAG: indexación y recuperación

Desglosará las dos fases de RAG: la fase de indexación offline, que divide, genera embeddings y almacena documentos, y la fase de recuperación online, que encuentra el contexto relevante para cada consulta.

La arquitectura RAG: indexación y recuperación es una lección gratuita de AI Engineering Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Engineering Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Engineering Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «La arquitectura RAG: indexación y recuperación» es gratis?

Sí — el texto completo de «La arquitectura RAG: indexación y recuperación» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Engineering Academy, actualiza a CoddyKit PRO. El curso de AI Engineering Academy incluye 4 lecciones en total.

¿Qué aprenderé en «La arquitectura RAG: indexación y recuperación»?

Desglosará las dos fases de RAG: la fase de indexación offline, que divide, genera embeddings y almacena documentos, y la fase de recuperación online, que encuentra el contexto relevante para cada co… Practicas AI Engineering Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar AI Engineering Academy?

No se requiere experiencia previa. AI Engineering Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «La arquitectura RAG: indexación y recuperación»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de AI Engineering Academy?

Sí. Cada lección de AI Engineering Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. El problema que resuelve RAG
  2. La arquitectura RAG: indexación y recuperación
  3. Creación del prompt aumentado
  4. RAG frente a fine-tuning: cuándo usar cada uno
← Volver a AI Engineering Academy