AlgoViz

Rewriting, filtering and re-ranking

medium 6 min

Query rewriting and expansion change what enters retrieval.

Video lesson · Chapter 1 of 4

The exception is eighth in line

0:00 / 3:26

Theory

Read or listen first. About 2 min.

What it is

Query rewriting and expansion change what enters retrieval. Filters determine eligibility. Re-ranking then orders an existing candidate set using a more expensive scoring function. Each stage operates on a different population of passages.

Why it exists

Record the correct passage’s rank before and after each stage. This shows whether it was absent from the corpus, removed by a filter, missed by retrieval, demoted by ranking or finally omitted by context packing.

The most relevant exception starts at rank eight

Shortlist → Pair scorer (score query and text). Pair scorer → Final selection (pack top results)
Shortlist → Pair scorer (score query and text). Pair scorer → Final selection (pack top results)

Inside this chapter

Chapter sources
Query Rewriting
A rewrite turns an ambiguous or conversational query into a query suitable for retrieval. Resolve “it” using conversation context while preserving identifiers, dates and exclusions. Compare the rewritten and original searches. A polished paraphrase that drops “before July” can retrieve a confidently wrong policy.

Conversational questions lean on earlier turns: pronouns, "that one", "the second option". A rewriter (usually a small model call) turns the latest turn into a standalone search query. The risk is that it paraphrases away the hard constraints, such as dates, negations, product codes and exclusions. Log the original and rewritten query, and check that every constraint in the original survives.

Example. Rewrite “Does that apply after July?” with conversation context. Keep the date qualifier and identify exactly which earlier policy “that” refers to.

Rewrite with context, keep the qualifiers

A fluent rewrite that drops after July would retrieve the wrong version.
Query Expansion
Query expansion generates related formulations and combines the resulting candidate sets. It can improve coverage for synonyms while increasing cost and introducing drift. Cap the number of expansions and retain which formulation retrieved each passage so you can inspect new false positives.

Expansion runs several versions of the query (synonyms, sub-questions, or model-generated variants) and merges their results, often with rank fusion. It recovers documents that use different words, but every extra variant costs a search and can pull in loosely related material. Cap the number of variants and evaluate the new results they add, not just the overall score.

Example. Expand “chargeback” into “disputed card charge” and “refund.” Inspect which new passages address disputes and which merely describe ordinary returns.

Expanding chargeback
  1. 1Original querychargeback
  2. 2Generate variantsdisputed card charge · refund
  3. 3Search each variant3 candidate lists
  4. 4Fuse and tag origineach passage keeps its variant
  5. 5Inspect new hitsrefund adds ordinary returns: drift

The dispute variant helps; the refund variant mostly adds false positives, so cap or drop it.

Re-ranking Strategies
A reranker scores query–passage pairs jointly after a cheaper first stage supplies a shortlist. It can promote an exception-bearing passage above generic policy text. It cannot rescue a document absent from the shortlist. Measure candidate recall first and final ranking quality second.

A bi-encoder embeds query and passage separately, which is fast but compresses each into one vector. A cross-encoder reads the query and passage together, so every query word can attend to every passage word; it is much more accurate at judging relevance but far too slow to run over the whole corpus. Hence the two-stage design: retrieve tens to hundreds cheaply, rerank them, keep the top few.

Example. Fix the first-stage shortlist and recompute ordering. Record the rank of a labeled exception before and after the cross-encoder runs.

Another example. A legal search tool retrieves 100 clauses with hybrid search and reranks them with a cross-encoder. The clause mentioning "force majeure excluding pandemics" jumps from rank 40 to 2 for a pandemic question, because the reranker reads the exclusion in context.

Before and after a cross-encoder

PassageFirst-stage rankRerankedContent
P112General returns policy
P323Return shipping labels
P881International returns exception
P21not retrievednever seenAlso relevant, lost
The reranker can promote P8 but cannot see P21.
Metadata Filtering
Metadata filters restrict eligible documents by fields such as tenant, product or effective date. Enforce authorization before text reaches the model and again when serving source links as appropriate. Filtering only a tiny post-search shortlist can leave no eligible matches despite relevant documents elsewhere.

Filtering after a small top-k is the classic bug: the global best matches belong to someone else, they are removed, and the user gets nothing even though relevant documents exist. Prefer engines that apply the filter during the search, or partition indexes per tenant. Apply authorisation again when serving a source link, because permissions can change between retrieval and click.

Example. The global top ten all belong to tenant B. Search tenant A’s eligible collection directly rather than returning an empty list after dropping all ten.

Pre-filter: search inside tenant A

  • Only eligible chunks compete for top k
  • Always returns tenant A's best matches
  • Authorisation enforced before ranking

Post-filter a global top 10

  • All 10 may belong to tenant B
  • Dropping them leaves an empty result
  • Ineligible text was scored and maybe logged
Maximal marginal relevance (MMR)
A selection rule that picks results one at a time, balancing relevance to the query against similarity to results already chosen, so the final set is not five copies of the same paragraph.

Duplicates are common in real corpora: the same clause appears in a policy, an FAQ and a help article. Pure relevance ranking fills the prompt with them and leaves no room for the qualifying passage. MMR penalises a candidate in proportion to how similar it is to something already picked. Tune λ on questions that need two different passages.

Example. Three near-identical chunks of the standard returns clause rank 1 to 3. MMR keeps one of them and promotes the holiday exception into the second slot.

Pick the next document

d∗=arg⁡max⁡d∈R∖S[λ sim(d,q)−(1−λ)max⁡s∈Ssim(d,s)]d^{*}=\arg\max_{d\in R\setminus S}\Big[\lambda\,\text{sim}(d,q)-(1-\lambda)\max_{s\in S}\text{sim}(d,s)\Big]
R is the candidate list, S the already selected set. λ = 1 is pure relevance; smaller λ rewards diversity.

How it works

Step through the idea, or press Play.

Step 1 of 3

Shortlist. 20 authorized passages

Understand it

Worked example

The most relevant exception starts at rank eight

  1. 1

    20 authorized passages

    One candidate contains the exception for international returns. A cheap retriever placed it eighth.

  2. 2

    P8 promoted to rank 1

    A cross-encoder evaluates the question together with each passage. Keep document IDs and scopes intact during reordering.

  3. 3

    Top 3 sent to generator

    With a fixed prompt budget, moving P8 into the top three changes what the generator can see. Evaluate this stage separately from candidate recall.

Follow the handoffs

Record the correct passage’s rank before and after each stage. This shows whether it was absent from the corpus, removed by a filter, missed by retrieval, demoted by ranking or finally omitted by context packing.
Where the exception's rank changes
  1. 1Filter20 authorised passages
  2. 2First stageP8 at rank 8
  3. 3Cross-encoderP8 promoted to rank 1
  4. 4Pack top 3P8 reaches the generator

Record P8's rank at every stage. Each stage has its own failure mode.

Summary

The whole topic in one minute.

A reranker orders the candidates it receives. It cannot score an omitted document.

Record the correct passage’s rank before and after each stage. This shows whether it was absent from the corpus, removed by a filter, missed by retrieval, demoted by ranking or finally omitted by context packing.

Sources