KatInterview

Build a Document Embedding Pipeline with Filtered Retrieval

Machine LearningModel answer
MediumModel answerMachine Learningembeddingsvector-searchml-systems

Last 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