Build a Document Embedding Pipeline with Filtered Retrieval
Machine LearningModel answerLast updated
Design ingestion and search functions for a vector-based document retrieval system with metadata filtering and production-grade error handling.
You're building the backend for a document search system that uses semantic embeddings. Your task is to write pseudocode for two functions: one that processes documents into searchable vectors, and one that retrieves relevant documents given a query.
Part 1: Document Processing Pipeline
Write a function ingest_documents(docs) where each document has the structure:
{'id': 'doc123', 'content': 'some text...', 'category': 'electronics'}
Requirements:
- Split documents longer than 512 tokens into smaller pieces (assume a
tokenize_and_split(text, max_len)helper exists) - Generate embeddings using
model.embed(text_list)which takes a list of strings and returns a list of vectors - Normalize all vectors to unit length for cosine similarity
- Store vectors with their metadata in a way that re-running the pipeline doesn't create duplicates
- Handle embedding failures gracefully (e.g., API timeouts, rate limits)
Part 2: Query Function
Write a function retrieve_documents(query_text, category, k=5) that:
- Converts the query into an embedding using the same model
- Finds the k most similar documents that match the category filter
- Returns results ranked by similarity
Assume a db.search(vector, metadata_filter, limit) interface exists.
Constraints
- Documents can be split into multiple chunks
- The embedding model may fail intermittently
- The same document ID may be ingested multiple times (updates)
- Category filters must be applied efficiently (not post-filtered)
What to address
- How do you ensure the pipeline can be safely re-run?
- How do you handle the fact that one document might become multiple chunks?
- What happens when embedding generation fails for some documents?
- How do you ensure query-time and index-time embeddings are comparable?
Hints
Hint 1
Make chunk identifiers deterministic so re-ingestion overwrites rather than duplicates
Hint 2
Normalize vectors at both indexing and query time to make cosine similarity work with dot product
Hint 3
Consider fetching more than k results at query time since multiple chunks from the same document may appear
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
This problem tests whether you understand the practical considerations of building a production embedding pipeline beyond just calling model.embed().
Core Architecture
The system has two paths that must stay synchronized:
Write path: document → chunks → embeddings → normalize → store with metadata
Read path: query → embedding → normalize → filtered search → deduplicate
Both paths must use identical preprocessing and normalization, or retrieval quality degrades.
Part 1: Ingestion Pipeline
The key challenges are idempotency, error isolation, and chunk management.
Idempotency through deterministic IDs:
When a document is split into chunks, assign each chunk an ID like doc123#0, doc123#1, etc. This makes chunk IDs a pure function of the document ID and chunk position. When you re-ingest doc123, the new chunks overwrite the old ones by ID rather than creating duplicates.
Stale chunk cleanup:
If a document previously had 5 chunks and now has 3, chunks #3 and #4 become stale. After upserting the new chunks, query for all existing chunk IDs matching doc_id = doc123 and delete any that aren't in the new set.
Batching and retry:
Process chunks in batches of 32–64 to amortize model overhead. Wrap the embedding call in retry logic with exponential backoff. If a batch fails after retries, fall back to processing its items individually so one bad input doesn't block 63 good ones. Track failed chunk IDs separately.
Normalization:
Compute L2 norm: norm = sqrt(sum(x^2 for x in vector)), then divide each component by the norm. This ensures ||v|| = 1, which makes dot product equivalent to cosine similarity. Check for zero-norm vectors and treat them as failures.
Pseudocode structure:
def ingest_documents(docs):
chunks = []
for doc in docs:
if not doc['content'].strip():
log_skip(doc['id'])
continue
pieces = tokenize_and_split(doc['content'], 512)
for i, piece in enumerate(pieces):
chunks.append({
'chunk_id': f"{doc['id']}#{i}",
'doc_id': doc['id'],
'text': piece,
'category': doc['category']
})
records, failed = [], []
for batch in batches(chunks, size=64):
try:
vectors = embed_with_retry([c['text'] for c in batch])
for chunk, vec in zip(batch, vectors):
normalized = normalize(vec)
records.append({
'id': chunk['chunk_id'],
'vector': normalized,
'doc_id': chunk['doc_id'],
'category': chunk['category']
})
except EmbeddingError:
# Fallback: try each item individually
for chunk in batch:
try:
vec = embed_with_retry([chunk['text']])[0]
# ... same as above
except:
failed.append(chunk['chunk_id'])
# Atomic upsert
db.upsert(records)
# Clean stale chunks
for doc_id in set(c['doc_id'] for c in chunks):
valid_ids = {c['chunk_id'] for c in chunks if c['doc_id'] == doc_id}
existing_ids = db.list_chunk_ids(doc_id=doc_id)
stale = existing_ids - valid_ids
if stale:
db.delete(list(stale))
return {'indexed': len(records), 'failed': failed}
Part 2: Retrieval Function
Query embedding:
Embed and normalize the query using the exact same process as ingestion. Skipping normalization or using a different model breaks similarity ranking.
Filtered search:
Pass the category filter into db.search() as a pre-filter. This ensures the vector index only considers matching documents. Post-filtering (retrieve top k, then filter) can return fewer results than requested even when matches exist.
Deduplication and oversampling:
Since one document can produce multiple chunks, the top k chunks might all come from 2 documents. Fetch k * oversample_factor results (e.g., 3–5x), then group by doc_id and pick the highest-scoring chunk per document. Return the top k documents.
Pseudocode:
def retrieve_documents(query_text, category, k=5):
if not query_text.strip():
return []
vec = model.embed([query_text])[0]
normalized = normalize(vec)
# Fetch extra to account for within-document duplicates
raw_results = db.search(
vector=normalized,
filter={'category': category},
limit=k * 4
)
# Deduplicate: keep highest-scoring chunk per document
doc_scores = {}
for result in raw_results:
doc_id = result['doc_id']
if doc_id not in doc_scores or result['score'] > doc_scores[doc_id]['score']:
doc_scores[doc_id] = result
ranked = sorted(doc_scores.values(), key=lambda x: x['score'], reverse=True)
return ranked[:k]
Why This Works
- Cosine similarity via dot product: After L2 normalization,
cos(a, b) = a · b / (||a|| ||b||) = a · bwhen||a|| = ||b|| = 1. This lets the DB use a fast inner-product index while ranking by cosine. - True idempotency: Deterministic chunk IDs + stale cleanup means running ingestion N times produces the same state as running it once.
- Graceful degradation: Batch-level retry with per-item fallback isolates failures. A single bad document doesn't crash the job.
- Correct filtering: Pre-filtering ensures all returned results match the category and the full k results can be returned when matches exist.
Complexity
Ingestion: O(N·d) for normalization where N = total chunks and d = embedding dimension. Model calls dominate in practice. Database writes are O(N).
Retrieval: One model call, O(d) normalization, and approximate nearest neighbor search (typically O(log M · d) for M stored vectors using HNSW).
Edge Cases to Handle
- Empty input: Return early without calling the model
- Zero-norm embeddings: Treat as a failure; don't divide by zero
- Model returns wrong number of vectors: Validate output length matches input
- All chunks fail for a document: Log the document ID but continue processing others
- Filter matches nothing: Return empty list, not an error
- Document shrinks on re-ingestion: Stale chunk cleanup prevents orphaned chunks
Common Mistakes
- Normalizing only at index time or only at query time: Both must be normalized or ranking breaks
- Post-filtering instead of pre-filtering: Inefficient and can return incomplete results
- Not deduplicating chunks: Returns redundant results from the same document
- Non-deterministic chunk IDs: Creates duplicates on re-ingestion
- No stale chunk cleanup: Old chunks persist forever, polluting search results
- Batch failure crashes entire job: Should isolate and retry failed items