#348Parent-Document RetrievalMedium

Parent-Document Retrieval

Background

Parent-document retrieval combines two wins: small chunks embed precisely, so they win at retrieval; large parents give the LLM enough context to ground the answer. The retriever returns chunk IDs; before generation, you map each chunk to its parent doc and dedupe.

Problem statement

Implement parent_retrieve(chunk_hits, chunk_to_parent, k). Walk chunk_hits in rank order, look up each chunk's parent, skip parents already seen, and stop at k distinct parents.

Input

  • chunk_hitslist[str], ranked retrieved chunk IDs (best first).
  • chunk_to_parentdict[str, str], chunk-id → parent-doc-id. Missing keys map to None and are silently skipped.
  • kint >= 0, desired parent count.

Output

Returns list[str] of length k\le k, distinct parents in first-seen order.

Examples

Example 1 — basic mapping + dedup

Input:
  chunk_hits = ["c1", "c2", "c3", "c4"]
  chunk_to_parent = {"c1": "p1", "c2": "p1", "c3": "p2", "c4": "p1"}
  k = 2
Output: ["p1", "p2"]

Example 2 — k > distinct parents

Input:  hits all map to p1; k=5
Output: ["p1"]

Example 3 — empty hits

Input:  [], {}, k=3
Output: []

Constraints

  • Hits not present in chunk_to_parent are silently dropped.
  • k = 0 → return [].
  • Output preserves first-seen order.

Notes

  • Why dedup. Two retrieved chunks from the same parent would feed the LLM the same context twice — wasted tokens and confusing for the model.
  • vs sentence-window retrieval. Same idea, different granularity — retrieve a sentence, expand to its surrounding paragraph at generation time.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • reference basic mapping and dedup
  • example missing chunks skipped
  • sample k cap after skipping a miss