Skip to content
Back to blog
AI system

Advanced Retrieval Strategies: Beyond Top-K Vector Search in Production RAG

Updated 23 min read

Top-K vector search is a good baseline, but complex questions need more than semantic similarity. A practical guide to query rewriting, hybrid search, metadata filtering, parent-child, multi-hop, and graph retrieval, using a contract analysis system as the example.

Table of Contents

Introduction

In the previous article ([TODO: link to previous article]), we built a production-oriented RAG pipeline:

  1. Parse and normalize documents.
  2. Split documents into chunks.
  3. Generate embeddings.
  4. Retrieve relevant passages.
  5. Rerank candidates.
  6. Assemble context.
  7. Generate grounded answers.

This architecture provides a solid foundation.

However, a basic retrieval implementation often looks like this:

typescript
const queryEmbedding = await embed(question);

const results = await vectorStore.search({
  vector: queryEmbedding,
  limit: 5,
});

It is simple, efficient, and useful for many questions.

But consider these questions in our AI Contract Analysis system:

  • Can the customer terminate this agreement without cause?
  • Does the termination right change if the customer has already renewed the agreement?
  • Which obligations survive termination, and how long do they remain effective?
  • Does the latest amendment override the original termination clause?

These are not all simple semantic similarity problems.

Some require multiple search expressions. Some require exact identifiers. Others require connecting information across several sections or documents.

A vector search can retrieve passages that sound relevant without retrieving all the evidence needed to answer the question.

The next step is to make retrieval more intelligent.

1. Why Simple Top-K Retrieval Breaks Down

A Top-K vector search returns the K candidates with the highest similarity scores to a query.

For example:

text
Query:
Can the customer terminate without cause?

Top 5:
1. Section 12.1 - Termination for Convenience
2. Section 12.2 - Termination for Cause
3. Section 18.4 - Notice Requirements
4. Section 9.3 - Service Suspension
5. Section 15.1 - Contract Expiration

This may look reasonable.

But it does not necessarily answer the complete question.

Perhaps an amendment changes Section 12.1. Perhaps Section 18.4 defines how notice must be delivered. Perhaps another clause introduces an exception.

The problem is that similarity and answer completeness are different things.

1.1 Five common retrieval failure patterns

FailureDescriptionExample
Vocabulary mismatchUser wording differs from source wording"Cancel early" vs. "terminate before expiration"
Exact-match failureSemantic search misses identifiers or exact termsSection 12.1 or a defined legal term
Context fragmentationRelated information is split across chunksA clause and its exception
Multi-document dependencyThe answer depends on several documentsAgreement plus amendment
Multi-hop dependencyOne fact is needed to discover anotherFind the applicable version, then retrieve its termination clause

These failures require different solutions.

Increasing Top-K may help with some of them, but it can also introduce more irrelevant passages, increase token usage, and make context assembly harder.

1.2 Retrieval should be question-aware

A useful retrieval architecture should not assume that every question requires the same search strategy.

flowchart TD
    A["User Question"] --> B["Question Analysis"]
    B --> C{"Question Type"}

    C -->|"Exact term or section"| D["Keyword Retrieval"]
    C -->|"Semantic question"| E["Vector Retrieval"]
    C -->|"Multiple concepts"| F["Multi-Query Retrieval"]
    C -->|"Specific document or version"| G["Metadata Filtering"]
    C -->|"Related sections"| H["Parent-Child Retrieval"]
    C -->|"Cross-document dependencies"| I["Multi-Hop Retrieval"]

    D --> J["Candidate Fusion"]
    E --> J
    F --> J
    G --> J
    H --> J
    I --> J

    J --> K["Reranking"]
    K --> L["Context Assembly"]

The question analysis stage does not need to be an expensive LLM call in every implementation.

It can start with deterministic rules, query classification, or a lightweight model. The appropriate level of sophistication should be established through evaluation.

2. Query Rewriting: Understanding What the User Really Needs

Users rarely formulate questions in the exact language used by source documents.

A user might ask:

Can we cancel the deal early?

But the agreement may use terms such as:

  • Termination for convenience.
  • Early termination.
  • Termination before the expiration date.
  • Customer termination rights.
  • Written notice of termination.

Query rewriting transforms the original question into a search-friendly representation while preserving its intent.

2.1 Basic query rewriting

flowchart LR
    A["Original Question"] --> B["Query Rewriter"]
    B --> C["Normalized Search Query"]
    C --> D["Retriever"]
    D --> E["Relevant Passages"]

For example:

text
Original:
Can we cancel the deal early?

Rewritten:
Find provisions describing the customer's right to terminate
the agreement before its expiration date, including termination
for convenience, notice periods, and applicable conditions.

The rewritten query is more explicit about the concepts that matter.

2.2 Implementing a query rewriting interface

Keep rewriting separate from retrieval so it can be tested independently.

typescript
interface QueryRewriter {
  rewrite(input: {
    question: string;
    conversationContext?: string;
  }): Promise<{
    searchQuery: string;
    keywords: string[];
  }>;
}

An implementation might use an LLM, but the output should be validated and constrained.

For example, the rewriter should not silently change:

Can the customer terminate without cause?

into:

How can the supplier terminate for breach?

That would be a semantic error, not an improvement.

The original question should remain available throughout the pipeline. The rewritten query is a retrieval aid, not a replacement for the user's intent.

2.3 Conversation-aware rewriting

Consider this conversation:

text
User: Can the customer terminate without cause?

Assistant: The agreement appears to allow termination
with a 60-day notice period.

User: What about during the first year?

The second question is incomplete when considered in isolation.

A conversation-aware rewriter can resolve it as:

text
Can the customer exercise the termination-for-convenience
right during the first year of the agreement?

This is especially useful in conversational RAG applications.

However, conversation context must be treated carefully. A previous assistant answer is not authoritative evidence about the contract. The system should use it to understand the follow-up question, then retrieve the underlying contractual provisions again.

2.4 When query rewriting is useful

Use it when:

  • Users ask vague or informal questions.
  • Source documents use domain-specific terminology.
  • Questions contain references to previous messages.
  • Search queries are consistently missing relevant passages.
  • Users ask questions in a different language from the documents.

Do not assume rewriting always improves retrieval. An overly broad rewrite can introduce irrelevant terms, while an overly specific rewrite can exclude relevant evidence.

Evaluate both the original and rewritten query against the same test set.

3. Multi-Query Retrieval: Searching from Multiple Perspectives

Sometimes a question contains several related concepts that should be searched independently.

For example:

What happens to the customer's rights and obligations after termination?

This could require finding:

  • Rights that survive termination.
  • Confidentiality obligations.
  • Outstanding payment obligations.
  • Data deletion or return requirements.
  • Indemnification obligations.
  • Liability provisions.

A single embedding may not represent all these concepts equally well.

Multi-query retrieval generates several search queries from the original question and executes them independently.

3.1 Multi-query architecture

flowchart TD
    A["Original Question"] --> B["Query Expansion"]

    B --> C["Query 1: Surviving Rights"]
    B --> D["Query 2: Payment Obligations"]
    B --> E["Query 3: Confidentiality"]
    B --> F["Query 4: Data Return"]

    C --> G["Retriever"]
    D --> G
    E --> G
    F --> G

    G --> H["Merge Results"]
    H --> I["Deduplicate"]
    I --> J["Rerank"]
    J --> K["Final Evidence"]

Each query searches for a different aspect of the question.

The results are then merged, deduplicated, and reranked.

3.2 A TypeScript implementation

typescript
interface SearchQuery {
  id: string;
  query: string;
}

interface SearchResult {
  chunkId: string;
  text: string;
  score: number;
}

interface Retriever {
  search(query: string): Promise<SearchResult[]>;
}

async function multiQuerySearch(
  queries: SearchQuery[],
  retriever: Retriever,
): Promise<SearchResult[]> {
  const resultSets = await Promise.all(
    queries.map(({ query }) => retriever.search(query)),
  );

  const unique = new Map<string, SearchResult>();

  for (const results of resultSets) {
    for (const result of results) {
      const existing = unique.get(result.chunkId);

      if (!existing || result.score > existing.score) {
        unique.set(result.chunkId, result);
      }
    }
  }

  return [...unique.values()];
}

This is a simplified example. It merges duplicate chunks but does not yet implement a robust ranking strategy across result sets.

In production, consider:

  • Reciprocal Rank Fusion.
  • Query-level relevance tracking.
  • Candidate limits per query.
  • Deduplication by canonical chunk identity.
  • Timeouts and partial-result handling.
  • Cost and latency budgets.

3.3 Multi-query is not the same as multi-hop retrieval

These techniques are often confused.

Multi-query retrieval searches for several aspects of a question, usually in parallel.

Multi-hop retrieval uses information discovered in one step to determine what to search for next.

For example:

text
Multi-query:
Search for termination rights, notice periods, and exceptions
in parallel.

Multi-hop:
Find the applicable amendment first.
Then use that amendment to determine which termination clause
must be retrieved.

The distinction becomes important when designing more advanced retrieval workflows.

4. Hybrid Search: Combining Semantic and Lexical Retrieval

Vector search is good at finding semantic relationships.

Keyword search is good at finding exact words, identifiers, and terminology.

For many enterprise applications, combining both is more reliable than depending on either one alone.

4.1 A practical example

Suppose the user asks:

What does Section 12.1 say about termination for convenience?

Vector search may retrieve other termination-related clauses.

Keyword search can directly identify Section 12.1.

Now consider:

Can the customer cancel without cause?

Vector search may recognize the relationship between "cancel without cause" and "termination for convenience", even when the exact phrase does not appear.

These approaches complement each other.

4.2 Hybrid retrieval flow

flowchart TD
    A["User Question"] --> B["Query Normalization"]

    B --> C["Lexical Search"]
    B --> D["Vector Search"]

    C --> E["BM25 Results"]
    D --> F["Semantic Results"]

    E --> G["Rank Fusion"]
    F --> G

    G --> H["Deduplicate"]
    H --> I["Reranker"]
    I --> J["Top Evidence"]

4.3 Why score fusion needs care

BM25 and vector similarity produce scores with different meanings and distributions.

A naive approach might add the scores directly:

typescript
const combinedScore = bm25Score + vectorScore;

This can produce misleading rankings because one score may dominate simply due to its scale.

Possible approaches include:

  • Normalize scores using a suitable method.
  • Use weighted ranking fusion.
  • Use Reciprocal Rank Fusion.
  • Train a ranking model if sufficient labeled data exists.

RRF is a practical starting point because it operates on result ranks rather than assuming that raw scores are comparable.

typescript
function reciprocalRankFusion(
  rankings: string[][], // each list: chunk IDs ordered best-first
  k = 60,
): Map<string, number> {
  const scores = new Map<string, number>();

  for (const ranking of rankings) {
    ranking.forEach((chunkId, index) => {
      const rank = index + 1;
      scores.set(chunkId, (scores.get(chunkId) ?? 0) + 1 / (k + rank));
    });
  }

  return scores;
}

A document ranked highly by both retrievers accumulates a higher score than one ranked highly by only one. The constant k dampens the influence of top ranks; 60 is the commonly used default.

4.4 Weighted retrieval

In some systems, we may want to give lexical search more influence for exact legal terminology.

A weighted ranking model could be expressed as:

text
score(d) = α · lexical(d) + β · semantic(d)

Where:

  • lexical(d) is the normalized lexical score of document d.
  • semantic(d) is the normalized semantic score of document d.
  • α and β are weights, often constrained so that α + β = 1.

The weights should be tuned against a representative evaluation dataset.

There is no universal value that works for every corpus.

5. Metadata Filtering: Retrieval Within the Right Context

Metadata filtering is one of the most important techniques in production RAG.

A system may contain millions of chunks, but a particular query should only search the documents that are relevant and authorized.

For our contract analysis platform, metadata may include:

typescript
interface RetrievalMetadata {
  tenantId: string;
  documentId: string;
  versionId: string;
  documentType: string;
  effectiveDate?: string;
  status: "active" | "superseded" | "archived";
}

This enables queries such as:

  • Search only contracts belonging to the current tenant.
  • Search only a specific agreement.
  • Exclude superseded versions.
  • Search only active policies.
  • Restrict retrieval to documents accessible to the current user.

5.1 Filtering should be part of retrieval

flowchart TD
    A["User Request"] --> B["Authorization Context"]
    B --> C["Build Retrieval Filters"]

    C --> D["Tenant Filter"]
    C --> E["Document Filter"]
    C --> F["Version Filter"]
    C --> G["Access Policy"]

    D --> H["Scoped Search"]
    E --> H
    F --> H
    G --> H

    H --> I["Authorized Results"]

A critical rule:

Do not retrieve unauthorized documents and ask the LLM to ignore them.

Authorization belongs in the application and data-access layers.

The model should never receive information the requesting user is not allowed to access.

5.2 Filtering and ranking are different

Filtering determines which records are eligible for retrieval.

Ranking determines which eligible records are most relevant.

These should be treated as separate operations.

For example, an active agreement may be eligible, while an archived agreement may be excluded. Among the eligible records, semantic and lexical ranking determine which clauses are relevant to the question.

5.3 Version resolution is especially important

Consider:

text
Original Agreement
  └── Section 12.1: 30 days' notice

Amendment 1
  └── Section 12.1: 45 days' notice

Amendment 2
  └── Section 12.1: 60 days' notice

A naive search might retrieve all three provisions.

The model may then see conflicting notice periods and produce an incorrect conclusion.

The system needs a document-version model that determines which provision is currently applicable.

This is not something vector similarity can solve reliably.

Version resolution should be an explicit business rule, potentially supported by document relationships and effective dates.

6. Parent-Child Retrieval: Precision Without Losing Context

Chunking creates a trade-off.

Small chunks can be precise but lack context.

Large chunks preserve context but can reduce retrieval precision.

Parent-child retrieval addresses this by searching small chunks and returning their larger parent sections when appropriate.

6.1 Architecture

flowchart TD
    A["Original Section 12"] --> B["Parent Chunk"]
    B --> C["Child Chunk 1"]
    B --> D["Child Chunk 2"]
    B --> E["Child Chunk 3"]

    F["User Query"] --> G["Search Child Chunks"]
    G --> H["Top Matching Children"]
    H --> I["Resolve Parent IDs"]
    I --> J["Load Parent Context"]
    J --> K["Assemble Evidence"]

For example, the child chunk might contain the exact termination provision, while the parent contains the surrounding section, definitions, and exceptions.

6.2 A simple data model

typescript
interface ParentChunk {
  id: string;
  documentId: string;
  sectionId: string;
  text: string;
}

interface ChildChunk {
  id: string;
  parentId: string;
  text: string;
  embedding: number[];
}

The child chunks are indexed for retrieval. The parent chunks are stored for context expansion.

A retrieval operation can then:

  1. Search child chunks.
  2. Select the most relevant candidates.
  3. Resolve their parent IDs.
  4. Load the corresponding parent sections.
  5. Deduplicate overlapping sections.
  6. Assemble the final evidence context.

6.3 When to use it

Parent-child retrieval is especially useful for:

  • Legal contracts.
  • Technical specifications.
  • API documentation.
  • Policies and procedures.
  • Long reports with hierarchical sections.

It is less useful when documents have no meaningful structure or when the parent sections are so large that context expansion becomes expensive.

7. Multi-Hop Retrieval: Connecting Evidence Across Documents

Some questions cannot be answered with a single retrieval operation.

They require discovering one piece of information, then using it to determine what information should be retrieved next.

This is multi-hop retrieval.

7.1 A contract analysis example

Consider the question:

Does the customer's termination right change under the latest amendment?

The system cannot answer this reliably by searching for "termination" alone.

It needs to:

  1. Identify the relevant agreement.
  2. Find amendments associated with that agreement.
  3. Determine which amendment is applicable.
  4. Find the termination provision in that amendment.
  5. Retrieve the original provision for comparison.
  6. Determine the effective rule.
flowchart TD
    A["User Question"] --> B["Identify Agreement"]
    B --> C["Find Related Amendments"]
    C --> D["Resolve Applicable Amendment"]
    D --> E["Retrieve Amended Provision"]
    E --> F["Retrieve Original Provision"]
    F --> G["Compare Relevant Terms"]
    G --> H["Generate Grounded Answer"]

This is a sequential dependency.

The result of an earlier retrieval step determines the next query.

7.2 Implementing a bounded retrieval workflow

typescript
interface Amendment {
  documentId: string;
  effectiveDate: string;
  status: "active" | "superseded";
}

interface AgreementRepository {
  findAmendments(
    agreementId: string,
  ): Promise<Amendment[]>;
}

interface ProvisionRepository {
  findProvision(input: {
    documentId: string;
    section: string;
  }): Promise<string | null>;
}

async function resolveTerminationProvision(input: {
  agreementId: string;
  agreementDocumentId: string;
  asOfDate: string; // ISO 8601, e.g. "2025-01-31"
  agreements: AgreementRepository;
  provisions: ProvisionRepository;
}) {
  const amendments = await input.agreements.findAmendments(
    input.agreementId,
  );

  // ISO 8601 dates compare correctly as strings.
  const inEffect = amendments
    .filter(
      (item) =>
        item.status === "active" &&
        item.effectiveDate <= input.asOfDate,
    )
    .sort((a, b) =>
      b.effectiveDate.localeCompare(a.effectiveDate),
    );

  const originalProvision =
    await input.provisions.findProvision({
      documentId: input.agreementDocumentId,
      section: "12.1",
    });

  // Walk amendments newest-first and stop at the first one
  // that actually modifies Section 12.1.
  for (const amendment of inEffect) {
    const amendedProvision =
      await input.provisions.findProvision({
        documentId: amendment.documentId,
        section: "12.1",
      });

    if (amendedProvision) {
      return {
        originalProvision,
        amendedProvision,
        applicableAmendment: amendment,
      };
    }
  }

  return {
    originalProvision,
    amendedProvision: null,
    applicableAmendment: null,
  };
}

This is illustrative business logic, not a universal method for resolving amendments.

Real agreements can contain partial amendments, replacement clauses, effective-date conditions, and amendment precedence rules. The system must model those rules explicitly and avoid assuming that the newest document automatically overrides every earlier provision.

7.3 Multi-hop retrieval needs boundaries

A system that keeps searching indefinitely can become expensive and unpredictable.

Define:

  • Maximum retrieval hops.
  • Maximum number of candidates per hop.
  • Allowed document relationships.
  • Query timeout.
  • Maximum context size.
  • Conditions for stopping.
  • A fallback when evidence remains incomplete.

The objective is not to create an autonomous search agent that explores everything. It is to resolve the dependencies needed to answer a specific question.

8. Knowledge Graph RAG: Retrieving Relationships, Not Just Text

Traditional vector retrieval focuses on passages and semantic similarity.

However, many enterprise questions depend on relationships between entities.

In contract analysis, entities may include:

  • Agreements.
  • Parties.
  • Amendments.
  • Clauses.
  • Obligations.
  • Effective dates.
  • Related documents.

A knowledge graph explicitly represents these relationships.

8.1 A simple contract knowledge graph

flowchart TD
    A["Service Agreement"] -->|"HAS_AMENDMENT"| B["Amendment 1"]
    A -->|"HAS_CLAUSE"| C["Section 12.1"]
    B -->|"MODIFIES"| C

    C -->|"DEFINES"| D["Termination Right"]
    D -->|"REQUIRES"| E["Notice Period"]

    A -->|"BETWEEN"| F["Customer"]
    A -->|"BETWEEN"| G["Supplier"]

Instead of retrieving only text that resembles the question, the application can traverse relationships.

For example:

text
Agreement
  → Has amendment
  → Amendment modifies Section 12.1
  → Section 12.1 defines termination right
  → Termination right requires notice period

This is useful when the question requires following known relationships.

8.2 Graph-based retrieval flow

flowchart LR
    A["User Question"] --> B["Entity and Relation Extraction"]
    B --> C["Graph Query"]
    C --> D["Related Entities"]
    D --> E["Resolve Source Documents"]
    E --> F["Retrieve Supporting Passages"]
    F --> G["LLM Generation"]

The graph can identify which documents and sections are related. The original document text can then provide the evidence needed for the final answer.

8.3 Graph RAG does not replace document retrieval

A knowledge graph may represent:

text
Amendment 2 MODIFIES Section 12.1

But the system still needs the actual text of Amendment 2 to explain what changed.

A graph relationship is not a substitute for source evidence.

A practical architecture often combines:

  • A relational database for authoritative entities and relationships.
  • A graph representation for relationship traversal where useful.
  • A search index for lexical retrieval.
  • A vector index for semantic retrieval.
  • Original documents for citation and verification.

Not every application needs a separate graph database. If the relationship model is simple, a relational schema and recursive queries may be sufficient.

8.4 When Knowledge Graph RAG is worth the complexity

Consider it when:

  • The corpus contains many interconnected entities.
  • Questions require traversing relationships.
  • Documents reference one another extensively.
  • Relationship queries are central to the application.
  • Explicit provenance between entities and source passages is valuable.

Avoid introducing a graph database simply because the system uses RAG.

If the majority of questions are straightforward semantic searches, a well-designed hybrid retrieval pipeline may be sufficient.

9. Combining Retrieval Strategies

These techniques are not mutually exclusive.

A production system can select and combine them based on the question.

For our contract analysis application, a practical architecture could look like this:

flowchart TD
    A["User Question"] --> B["Question Analysis"]
    B --> C["Query Rewriting"]

    C --> D["Metadata and Authorization Filters"]
    D --> E["Hybrid Retrieval"]

    E --> F["Candidate Fusion"]
    F --> G["Reranking"]

    G --> H["Parent Context Expansion"]
    H --> I{"Cross-Document Dependency?"}

    I -->|Yes| J["Multi-Hop or Graph Retrieval"]
    I -->|No| K["Context Assembly"]

    J --> K
    K --> L["LLM Generation"]
    L --> M["Evidence and Citation Validation"]
    M --> N["Final Answer"]

A key design principle is to avoid running every strategy for every query.

For example:

Question typeSuggested retrieval strategy
"What does Section 12.1 say?"Metadata filtering + keyword search
"Can the customer cancel early?"Query rewriting + hybrid retrieval
"What obligations survive termination?"Multi-query retrieval
"What does the latest amendment change?"Version resolution + multi-hop retrieval
"Which agreements reference this supplier?"Structured relationship query or graph traversal
"What does this clause mean in context?"Child retrieval + parent expansion

The retrieval strategy should be driven by the question and the application's requirements.

10. Evaluating Advanced Retrieval

Adding more retrieval strategies does not automatically improve quality.

Each strategy should be evaluated against a baseline.

10.1 Build a retrieval evaluation dataset

For each test question, record:

  • Original question.
  • Relevant document IDs.
  • Expected document versions.
  • Relevant section IDs.
  • Relevant evidence passages.
  • Expected answer or answer constraints.

For example:

typescript
interface RetrievalTestCase {
  question: string;
  expectedDocumentIds: string[];
  expectedSectionIds: string[];
  expectedEvidenceIds: string[];
  expectedStatus:
    | "supported"
    | "insufficient_evidence"
    | "conflicting_evidence";
}

This allows us to test whether retrieval finds the required evidence before involving the generation model.

10.2 Compare strategies independently

ExperimentRetrieval configurationWhat it measures
ATop-K vector searchBaseline
BQuery rewriting + vector searchVocabulary mismatch
CHybrid searchSemantic and exact-match coverage
DHybrid + rerankingCandidate ranking quality
EParent-child retrievalContext completeness
FMulti-hop retrievalCross-document dependencies
GGraph-assisted retrievalRelationship traversal

Track:

  • Recall@K.
  • Precision@K.
  • MRR or nDCG.
  • Correct document-version retrieval.
  • Context completeness.
  • End-to-end answer correctness.
  • Citation accuracy.
  • Latency and cost.

A strategy should be retained when it improves the relevant quality metric enough to justify its operational overhead.

10.3 Evaluate difficult cases, not only average cases

A retrieval system can perform well on simple questions and still fail on important edge cases.

Include tests for:

  • Conflicting clauses.
  • Superseded amendments.
  • Exact section references.
  • Synonyms and paraphrases.
  • Long-distance references.
  • Missing evidence.
  • Similar clauses in unrelated agreements.
  • Cross-tenant access boundaries.

In enterprise systems, security tests should be separate from relevance metrics. A retrieval system that returns highly relevant but unauthorized evidence is still fundamentally broken.

11. Production Design: Avoiding Unnecessary Complexity

Advanced retrieval introduces more components, more dependencies, and more failure modes.

The architecture should evolve based on measured problems.

11.1 Start with a retrieval capability ladder

flowchart TD
    A["Baseline: Top-K Search"] --> B{"Relevant Evidence Found?"}

    B -->|No| C["Check Parsing and Chunking"]
    B -->|Yes, Poor Ranking| D["Add Reranking"]

    C --> E{"Exact Terms or Identifiers Missed?"}
    E -->|Yes| F["Add Hybrid Search"]
    E -->|No, Wording Mismatch| G["Add Query Rewriting or Expansion"]

    D --> H{"Context Incomplete?"}
    F --> H
    G --> H

    H -->|Yes| I["Add Parent-Child Retrieval"]
    H -->|No| J["Evaluate End-to-End"]

    I --> K{"Cross-Document Dependency?"}
    K -->|Yes| L["Add Bounded Multi-Hop or Graph Retrieval"]
    K -->|No| J

    L --> J

This is a troubleshooting path, not a requirement to implement every component in sequence.

11.2 Keep retrieval observable

For each query, record enough information to understand how the result was produced:

typescript
interface RetrievalTrace {
  requestId: string;
  originalQuery: string;
  rewrittenQueries: string[];

  candidateCount: number;
  selectedChunkIds: string[];

  retrievalStrategy: string;
  rerankingApplied: boolean;
  contextTokenCount: number;

  durationMs: {
    rewriting: number;
    retrieval: number;
    reranking: number;
    contextAssembly: number;
  };
}

The trace should avoid storing sensitive document text unnecessarily.

A good trace helps answer questions such as:

  • Did query rewriting change the user's intent?
  • Did the correct document enter the candidate set?
  • Was the amendment filtered out?
  • Did reranking demote the right clause?
  • Was the parent section loaded?
  • Did context assembly exceed its budget?

Without this visibility, improving retrieval becomes guesswork.

11.3 Manage latency through selective execution

Not every request needs multi-query retrieval, reranking, and graph traversal.

A simple question might use a fast path:

text
Question
  → Authorization and metadata filtering
  → Hybrid retrieval
  → Context assembly
  → LLM
  → Output validation

A complex question might use a deeper path:

text
Question
  → Query analysis
  → Authorization and metadata filtering
  → Multi-query retrieval
  → Version resolution
  → Multi-hop retrieval
  → Reranking
  → Context assembly
  → LLM
  → Output validation

This architecture allows the application to balance answer quality, latency, and cost.

The fast path should not bypass authorization, provenance, or output validation. Those are foundational requirements, not optional advanced features.

11.4 Do not confuse retrieval complexity with intelligence

A pipeline with seven retrieval stages is not automatically better than one with two.

Every additional stage should answer a concrete engineering question:

  • What failure does this stage address?
  • How will we measure its impact?
  • What happens when it fails?
  • What is its latency and cost?
  • Can we disable it safely?
  • Does it introduce new security risks?

If those questions have no clear answers, the component may be unnecessary.

Summary

Simple Top-K vector search is a useful baseline, but it is not sufficient for every production RAG workload.

Advanced retrieval strategies address different failure patterns:

  • Query rewriting improves search queries when user wording differs from source terminology.
  • Multi-query retrieval searches multiple aspects of a complex question.
  • Hybrid search combines semantic and exact-term retrieval.
  • Metadata filtering restricts search to the correct documents, versions, and authorization scope.
  • Parent-child retrieval combines precise matching with surrounding context.
  • Multi-hop retrieval follows dependencies across retrieval steps.
  • Knowledge Graph RAG uses explicit relationships to find connected information.

For our contract analysis system, the strongest design is not necessarily the most complicated one.

Start with reliable document processing and hybrid retrieval. Add parent-child retrieval when context fragmentation becomes a problem. Introduce multi-hop or graph-based retrieval only when questions genuinely depend on relationships across documents.

The most important principle is this:

Retrieval quality is not about finding text that looks similar to a question. It is about finding the evidence necessary to answer that question correctly.

In the next article, we will move from retrieval into the next major challenge: LLM Agents and Tool Calling — how an AI system moves beyond retrieving information and begins selecting tools, executing workflows, and interacting with external systems in a controlled way.

  • hybrid search
  • query rewriting
  • multi-query retrieval
  • parent-child retrieval
  • multi-hop RAG
  • Knowledge Graph RAG
  • vector search
  • Production AI architecture
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading