0Pricing
AI Engineering Academy · 课时

RAG 架构:索引与检索

梳理 RAG 的两个阶段:离线索引阶段对文档进行分块、嵌入和存储;在线检索阶段为每个查询找到相关上下文。

RAG 架构:索引与检索 是 CoddyKit 上的免费 AI Engineering Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Engineering Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Engineering Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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.

常见问题解答

「RAG 架构:索引与检索」课时是免费的吗?

是的 — 「RAG 架构:索引与检索」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Engineering Academy 课程的其余内容,请升级到 CoddyKit PRO。 AI Engineering Academy 课程共包含 4 节课。

「RAG 架构:索引与检索」这节课中我会学到什么?

梳理 RAG 的两个阶段:离线索引阶段对文档进行分块、嵌入和存储;在线检索阶段为每个查询找到相关上下文。 你通过在浏览器中直接运行的动手代码来练习 AI Engineering Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Engineering Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Engineering Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「RAG 架构:索引与检索」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Engineering Academy 课中编写并运行代码吗?

能。每节 AI Engineering Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. RAG 解决的问题
  2. RAG 架构:索引与检索
  3. 编写增强提示
  4. RAG 与微调:何时选择哪一种
← 返回 AI Engineering Academy