A retrieval-augmented generation (RAG) pipeline ingests documents, splits them into chunks, embeds and indexes those chunks, retrieves and reranks matches, then generates an answer. Start with extraction and a simple retrieval baseline. Create a fixed set of questions before tuning, then measure retrieval again after adding each layer.
The seven components
See the RAG pipeline diagram for a visual walkthrough of the indexing and query paths.
| Stage | Decides | Cheapest to fix |
|---|---|---|
| Ingestion and extraction | Whether structure survives | At the start |
| Chunking | The retrieval unit | At the start |
| Embedding | What “similar” means | Before indexing |
| Vector index | Recall and latency at scale | Before scale |
| Retrieval and filtering | Which candidates exist | Any time |
| Reranking | Which candidates reach the model | Late |
| Generation and evaluation | What the user sees | Continuously |
Check each stage’s output before adding the next.
Ingestion and extraction
Flattening a PDF to plain text can lose heading levels, table boundaries, and reading order. If the extracted text mixes two columns, fix the extraction before splitting it into chunks.
Aim for Markdown or HTML with the heading hierarchy intact. The LlamaIndex framework documentation shows how parsed Markdown pages can feed a vector index. Inspect the extractor’s output before choosing it.
- Heading fidelity. Do H2 and H3 levels come out as headings, or as bold paragraphs indistinguishable from body text?
- Table handling. Are tables emitted as tables, or as a stream of cells with the header row orphaned somewhere above?
- Reading order. Two-column PDFs and sidebars are where extractors interleave text most visibly.
Assign each document a stable ID and store a content hash to detect changes. With a document store and vector store attached, the LlamaIndex ingestion pipeline skips unchanged documents and reprocesses documents whose hashes have changed.
Chunking
Chunking sets the unit the retriever returns. Keep related text together so a retrieved chunk can carry the context needed to answer a question.
Start by splitting on document structure and putting the heading path before the chunk text. For starting sizes, overlap, and metadata by content type, see the RAG chunking strategy guide. Splitter code and a recall-at-token-budget metric are in how to chunk text for RAG.
Pick a starting chunk size and measure retrieval on the fixed question set before changing it. Keep the same questions and expected source passages when comparing chunk sizes.
Embedding
Choose an embedding width, a distance metric, and a model before building the index.
Dimensionality. By default, OpenAI’s text-embedding-3-small returns 1,536 dimensions and text-embedding-3-large returns 3,072. Both accept up to 8,192 input tokens and support a dimensions parameter to shorten the output. OpenAI embeddings guide
Check the index limit for the storage type. pgvector’s vector type stores up to 16,000 dimensions, and its HNSW index supports up to 2,000 dimensions for vector or 4,000 for halfvec. pgvector documentation
Distance metric. Follow the embedding provider’s recommendation. OpenAI recommends cosine similarity for its unit-length embeddings. Dot product gives the same cosine similarity values for those vectors, and Euclidean distance gives the same ranking. OpenAI embeddings guide
Model family. Use the same model for documents and queries. To evaluate a different model, embed the documents with it, build a new index, and compare retrieval on the same questions.
Estimate the cost and index footprint before you commit. The chunk calculator converts a corpus size, chunk size, overlap ratio, and embedding width into a vector count, index RAM, and one-time embedding spend.
Vector index
Choose a vector store and the index to use in it.
Use an exact scan as the reference for measuring approximate search recall. Compare latency and recall on your own workload before choosing HNSW. In Qdrant, m controls graph connections, ef_construct controls the search range during index construction, and ef controls it at query time. Qdrant indexing guide
For a Qdrant collection, multiply the point count by the replication factor to get the total number of stored points. For dense float32 vectors, multiply that total by the number of dimensions and 4 bytes to get the raw vector size. Budget separately for HNSW, payload storage, and payload indexes. Quantisation can save RAM when compressed vectors stay in memory and the originals are kept on disk for rescoring. Qdrant capacity planning guide
Compare deployment options and filtering behaviour when choosing a store. That comparison is in Qdrant vs Milvus vs Pinecone.
Retrieval and filtering
Retrieval is where two features earn their keep.
Metadata filtering. Include the requested product version in the retrieval filter so the generator receives material for that version. Check how your store handles filters with approximate indexes. Qdrant can apply filters during HNSW traversal, while pgvector documents that filtering can leave fewer results after an approximate index scan. Qdrant indexing guide · pgvector documentation
Hybrid search. Combine lexical search for literal matches such as error codes with dense search for related wording. Reciprocal rank fusion combines the result lists using each candidate’s position in each list. Qdrant hybrid queries guide
Reranking
A cross-encoder reranker scores the query and each candidate chunk together. Run it on a shortlist, then pass the highest-ranked chunks to the generator. The Sentence Transformers guide uses 100 candidates as an example and shows how to return the top five passages. Sentence Transformers retrieve and rerank guide
Check whether the retriever found the relevant chunk before tuning the reranker. If it is missing from the candidate list, inspect chunking, embedding, and filtering first.
Generation and evaluation
Check both the context passed to the generator and the answer it produces.
Context ordering. Start with the reranked order. If you try a different arrangement, use the same passages and questions so you can compare the effect of ordering.
Grounding instructions. Tell the model to answer only from the provided context and to say when the context does not contain the answer.
Before tuning, assemble a fixed set of real questions and label the source passages that answer each one. Run the questions through retrieval and compare the returned chunks with the labels. Track recall at your chosen cutoff, nDCG, and mean reciprocal rank (MRR). LlamaIndex retrieval evaluation guide
Use faithfulness and response relevancy to evaluate generated answers. Use context precision and context recall to evaluate the retrieved material. Record the results for each stage so you can tell where a change helped. Ragas metrics documentation
The build order in practice
- Fix extraction until headings and tables survive.
- Chunk on structure with a defensible default size.
- Embed with one model, correct metric, and a width the index supports.
- Set up exact search as a reference and compare HNSW if you need lower latency.
- Run the fixed question set and record baseline recall@k.
- Add filtering and hybrid search. Run the same questions again.
- Add reranking and check retrieval and answer quality again.
- Only now tune chunk size, overlap, and embedding model, one at a time.
Changes to chunk boundaries or the embedding model can require rebuilding the index. Compare each change against the baseline using the same questions and expected source passages.
If recall stays flat, inspect the output at each stage. See RAG retrieval debugging.
Evidence and limits. The build order is based on the OpenAI text-embedding-3 guide, the pgvector README, Ragas’s stable documentation, and the online Qdrant, LlamaIndex, and Sentence Transformers guides. The steps were not run for this article.