Leanpub Header

Skip to main content

Embeddings and Reranking in Retrieval-Augmented Generation

Building Production-Grade Search Systems with Dense Retrieval and Neural Reranking

Embeddings and Reranking in Retrieval-Augmented Generation
This book is 100% completeLast updated on 2026-09-27

Build reliable, production-ready search systems with embeddings and neural reranking. Learn how to turn semantic meaning into relevant results, refine retrieved content and deliver better context for AI-generated answers. With hands-on Python examples and practical architectures, this book takes you from core concepts to real-world RAG systems.

Minimum price

$19.00

$29.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
216
Pages
About

About

About the Book

This book teaches you how to design, implement, and operate retrieval-augmented generation systems that work reliably in production. You will learn how embedding models represent semantic meaning as vectors, how different retrieval strategies exploit those representations, how reranking models refine candidate sets into high-quality context, and how to assemble these components into systems that are accurate, fast, and maintainable. The material assumes working knowledge of Python and basic machine learning concepts, and provides end-to-end code examples using real libraries, real models, and real architectural patterns.

Bundle

Bundles that include this book

Author

About the Author

Steve Publications

Steve is a technology professional with more than 20 years of experience in software development, server infrastructure, cybersecurity, vulnerability research and reverse engineering. Throughout his career, he has designed, secured, analyzed and tested complex software and infrastructure, with a particular focus on understanding how systems fail and how they can be made more secure.

Outside of work, Steve enjoys sharing knowledge with the technology community. He collaborates with researchers, industry experts and technology professionals to write practical books covering software development, cybersecurity, cloud computing, networking, DevOps, artificial intelligence and enterprise technologies. His books focus on practical learning through clear explanations, real-world examples and hands-on exercises. With more than two decades of industry experience, his goal is to help IT professionals, students and technology enthusiasts build useful skills and stay current in a rapidly changing industry.

We believe readers deserve to know how our books are created. Most of our authors are not native English speakers, so we use AI to help translate, proofread manuscripts, fix grammar, improve sentence structure and make technical explanations easier to read. AI is used as an editing tool only. It does not replace the research, technical knowledge or hands-on experience behind our books. Some of our authors also prefer to remain anonymous for privacy or professional reasons. In those cases, we publish their work under a different name. The author's name may be different, but the quality of the content and our review process remain the same.

Every book is written, reviewed and maintained by experienced technology professionals, with contributions from our private technical community of more than 420 engineers and researchers. We spend far more time validating technical accuracy and keeping our content up to date than generating text. We are always interested in working with experienced professionals who have deep expertise in a particular technology or domain. If you would like to publish a book with us or help review an existing manuscript, we'd love to hear from you. Send us a message describing your area of expertise. We are especially interested in niche technologies, specialized skills and emerging topics that are underrepresented in existing technical literature.

If you look through the contents of our books, you'll see practical examples, detailed explanations and material that is regularly updated. Our goal is to publish books that professionals can actually rely on, not low-effort AI-generated content. If you ever feel that one of our books does not meet that standard, Leanpub offers a 60-day money-back guarantee. Feel free to request a refund if you are not satisfied with your purchase.

Contents

Table of Contents

Building Production-Grade Search Systems with Dense Retrieval and Neural Reranking

Introduction: Why RAG Needs Better Retrieval

Chapter 1: The RAG Paradigm

  1. The Retrieval-Then-Generate Architecture
  2. Why Retrieval Quality Determines Output Quality
  3. The Complete RAG Data Flow
  4. RAG vs Finetuning vs Full Pretraining
  5. Common Pitfalls and Misconceptions
  6. What This Book Will Build

Chapter 2: Vector Representations and Similarity

  1. From Tokens to Vectors: The Basic Idea
  2. Embedding Spaces and Semantic Geometry
  3. Cosine Similarity, Dot Product, and Euclidean Distance
  4. Normalization and Its Effects on Similarity
  5. High-Dimensional Geometry: What Goes Wrong at Large Dimensions
  6. Choosing a Similarity Metric for Your Use Case

Chapter 3: Embedding Model Architectures

  1. Transformer Encoders as Embedding Backbones
  2. Bi-Encoder vs Cross-Encoder Architectures
  3. Late-Interaction Models and ColBERT
  4. Training Objectives: Contrastive Learning, Triplets, and Hard Negatives
  5. Mean-Pooling, CLS Tokens, and Output Strategies
  6. Instruction-Aware and Prompt-Based Embeddings

Chapter 4: Dense Retrieval vs Sparse Retrieval

  1. TF-IDF and BM25: Sparse Retrieval Fundamentals
  2. How Dense Retrieval Works Under the Hood
  3. The Lexical vs Semantic Gap
  4. When Sparse Beats Dense (and Vice Versa)
  5. Hybrid Search: Combining Dense and Sparse Signals
  6. Reciprocal Rank Fusion and Other Fusion Strategies

Chapter 5: Document Preprocessing and Text Normalization

  1. Document Parsing: PDFs, HTML, Office Files, and Code
  2. Text Cleaning and Normalization Strategies
  3. Handling Special Characters, Numbers, and Dates
  4. Language Detection and Multilingual Preprocessing
  5. Metadata Extraction and Structuring
  6. Common Preprocessing Mistakes That Hurt Retrieval

Chapter 6: Context Chunking Strategies — Part I: Foundational Methods

  1. Why Chunking Is The Most Underappreciated RAG Decision
  2. Fixed-Size Chunking: The Baseline Everyone Starts With
  3. Sentence-Based and Paragraph-Based Chunking
  4. Sliding-Window Chunking and Overlap Strategies
  5. Recursive Character Text Splitting
  6. Choosing Chunk Size and Overlap: Evidence-Based Guidance

Chapter 7: Context Chunking Strategies — Part II: Advanced Methods

  1. Semantic Chunking: Cluster-Based and Boundary Detection Methods
  2. Hierarchical Chunking and Parent-Document Retrieval
  3. Structure-Aware Chunking for Markdown, HTML, and Code
  4. Query-Aware and Dynamic Chunking
  5. Long-Context Chunking for Large Language Models
  6. Evaluating Chunking Quality: Metrics and Methods

Chapter 8: Vector Indexing and Approximate Nearest Neighbor Search

  1. Exact Nearest Neighbor vs Approximate Nearest Neighbor
  2. HNSW: The Workhorse of Modern Vector Search
  3. IVF, Product Quantization, and Other Indexing Strategies
  4. Index Build Time vs Query Latency Trade-Offs
  5. Choosing m, ef_construction, ef_search: Practical Tuning
  6. Vector Database Selection: Pinecone, Weaviate, Qdrant, Milvus, and More

Chapter 9: Building the Ingestion Pipeline

  1. Pipeline Architecture: Batch vs Streaming vs Hybrid
  2. Document Loading and Format Handling
  3. Chunking, Embedding, and Indexing as Distinct Stages
  4. Error Handling and Dead Letter Queues
  5. Incremental Updates and Document Versioning
  6. Scalable Ingestion Patterns for Large Corpora

Chapter 10: Query Processing and Expansion

  1. Understanding the Query: Intent, Ambiguity, and Reformulation
  2. Query Embedding with the Same or Different Models
  3. Query Expansion: HyDE, StepBack, and Similar Techniques
  4. Multi-Query Retrieval and Ensemble Queries
  5. Query Classification and Routing
  6. Handling Multi-Turn Conversational Queries

Chapter 11: Candidate Retrieval Strategies

  1. Single-Stage Dense Retrieval
  2. Hybrid Retrieval: Dense Plus Sparse Combined
  3. Multi-Vector Retrieval and ColBERT-Style Approaches
  4. Metadata Filtering and Faceted Search
  5. Semantic Search with Numerical and Temporal Filters
  6. Controlling Recall: How Many Candidates to Retrieve

Chapter 12: Reranking Models: Theory and Architectures

  1. Why Reranking Improves Retrieval Quality
  2. Cross-Encoder Reranking: Architecture and Mechanics
  3. Bi-Encoder vs Cross-Encoder vs Late-Interaction for Reranking
  4. Training Rerankers: Pairwise, Listwise, and Pointwise Methods
  5. Domain Adaptation and Fine-Tuning Rerankers
  6. Latency vs Accuracy: When Is Reranking Worth It

Chapter 13: Reranking Model Implementations

  1. Using Off-the-Shelf Rerankers (BGE, Cohere, Jina, E5)
  2. Batch vs Streaming Reranking Architectures
  3. Prompt-Based Reranking and LLM Reranking
  4. Adaptive and Conditional Reranking
  5. Cascaded and Multi-Stage Reranking Pipelines
  6. Cost Optimization for Reranking at Scale

Chapter 14: Context Assembly and Prompt Construction

  1. Selecting Which Chunks to Include
  2. Ordering Chunks: Recency, Relevance, and Narrative Flow
  3. Context Window Budgeting and Truncation Strategies
  4. Adding Source Attribution and Chunk Metadata
  5. Dynamic Context Selection Based on Query Complexity
  6. Prompt Templates That Make Retrieved Context Work

Chapter 15: End-to-End RAG System Design

  1. The Complete RAG Architecture: All Components Together
  2. Service Boundaries and API Design
  3. Synchronous vs Asynchronous Request Flow
  4. Caching Strategies for Embeddings and Retrieval Results
  5. Rate Limiting and Backpressure Handling
  6. Multi-Tenant and Multi-Index Architectures

Chapter 16: Evaluating Embedding and Reranking Models

  1. Retrieval Metrics: Recall@K, Precision@K, MRR, MAP, NDCG
  2. Building Evaluation Datasets: Queries and Ground Truth
  3. Model Selection Through Systematic Benchmarking
  4. Evaluating Without Ground Truth: Heuristics and Proxies
  5. A/B Testing Retrieval Quality in Production
  6. Ablation Studies and Controlled Experiments

Chapter 17: Evaluating End-to-End RAG Performance

  1. Answer Correctness and Factual Accuracy
  2. Faithfulness and Groundedness: Did the Answer Use the Context?
  3. Context Utilization and Relevance Scores
  4. Latency, Throughput, and Cost as Quality Metrics
  5. Automated Evaluation Frameworks (RAGAS, DeepEval, etc.)
  6. Human Evaluation Design and Execution

Chapter 18: Advanced Optimization Techniques

  1. Optimizing Embedding Dimensionality and Model Size
  2. Quantization and Compression for Embeddings
  3. GPU Acceleration and Batch Inference Patterns
  4. Distributed Vector Indexing and Shard Management
  5. Memory-Optimized Retrieval Architectures
  6. Throughput and Latency Optimization Checklist

Chapter 19: Debugging and Troubleshooting RAG Systems

  1. The RAG Debugging Playbook: Where to Start
  2. Diagnosing Bad Retrieval: Query, Index, or Model?
  3. Identifying Chunking Failures and Context Gaps
  4. Spotting Reranking Degradation and Cascading Errors
  5. Hallucination Diagnosis and Mitigation
  6. Logging, Tracing, and Observability Patterns

Chapter 20: Production Deployment and Operations

  1. Infrastructure and Containerization
  2. Model Serving: Triton, vLLM, and Custom Endpoints
  3. Monitoring: Metrics, Alerts, and Dashboards
  4. Versioning Models, Embeddings, and Chunking Logic
  5. Rollback Strategies and Canary Releases
  6. Disaster Recovery and Index Backups

Chapter 21: Security, Privacy, and Access Control

  1. Access Control and Document-Level Permissions
  2. PII Detection and Redaction in RAG Pipelines
  3. Prompt Injection and Retrieval Poisoning Attacks
  4. Data Isolation in Multi-Tenant Systems
  5. Audit Logging and Compliance Requirements
  6. Securing Embeddings Against Reconstruction Attacks

Chapter 22: Case Studies and Industry Patterns

  1. Enterprise Knowledge Base Search
  2. Code Documentation and Code Search
  3. Customer Support and Helpdesk Automation
  4. Legal Document Retrieval and Case Research
  5. Medical and Scientific Literature Search
  6. E-Commerce Product Search and Recommendations

Chapter 23: Future Directions and Open Problems

  1. Long-Context Models and Their Impact on RAG
  2. Multimodal RAG: Images, Audio, and Video in the Pipeline
  3. Self-Correcting RAG and Agentic Retrieval Patterns
  4. Learned Chunking and Neural Document Structure
  5. The Future of Reranking: Are Cross-Encoders Obsolete?
  6. Open Questions and Research Frontiers

Conclusion: Building RAG Systems That Work

  1. The Retrieval Stack in One Picture
  2. Decision Framework for Your RAG Architecture
  3. Common Anti-Patterns to Avoid
  4. How to Stay Current in a Fast-Moving Field
  5. Final Thoughts on Engineering Excellence in RAG

References

  1. Foundational Papers
  2. Chunking and Document Processing
  3. Query Processing and Expansion
  4. Embedding and Reranking Models
  5. Benchmarks and Evaluation
  6. Infrastructure and Optimization
  7. Security and Access Control
  8. Technical Articles and Guides

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub