惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Proofpoint News Feed
人人都是产品经理
人人都是产品经理
S
Schneier on Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
PCI Perspectives
PCI Perspectives
Vercel News
Vercel News
GbyAI
GbyAI
MongoDB | Blog
MongoDB | Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
I
Intezer
U
Unit 42
Recent Announcements
Recent Announcements
博客园 - 叶小钗
A
Arctic Wolf
H
Help Net Security
P
Palo Alto Networks Blog
MyScale Blog
MyScale Blog
Schneier on Security
Schneier on Security
The Hacker News
The Hacker News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
B
Blog RSS Feed
T
The Exploit Database - CXSecurity.com
L
Lohrmann on Cybersecurity
量子位
美团技术团队
S
Security Archives - TechRepublic
V
V2EX - 技术
M
MIT News - Artificial intelligence
Know Your Adversary
Know Your Adversary
C
Comments on: Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Martin Fowler
Martin Fowler
Engineering at Meta
Engineering at Meta
罗磊的独立博客
T
Threat Research - Cisco Blogs
P
Proofpoint News Feed
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
NISL@THU
NISL@THU
博客园 - Franky
J
Java Code Geeks
Webroot Blog
Webroot Blog
K
Kaspersky official blog
Cloudbric
Cloudbric
IT之家
IT之家

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Query Rewriting Before Retrieval: The Cheap Recall Win Most Skip
Gabriel Anhaia · 2026-06-14 · via DEV Community

A user types "how do I cancel" into your support bot. Your retriever embeds those three words, runs a cosine search, and hands the model five chunks about cancelling a payment, cancelling a meeting invite, and the word "cancel" appearing in a changelog. The chunk about cancelling a subscription, the thing the user actually wanted, ranked seventh. The model answers from what it got. The answer is wrong, and nobody on your team can see why.

The query was the problem. It was too short, too ambiguous, and missing the context the corpus was written with. Most teams reach for a bigger embedding model or a reranker to fix this. Both help. Both are more expensive than the thing that fixes the query before it ever hits the index: query rewriting.

Query rewriting sits in front of retrieval. You take the raw user query, run it through one cheap LLM call, and search with something better. Two patterns carry most of the win: multi-query expansion and step-back rewriting. Here is how each works, what it costs, and how to decide whether the latency is worth it.

Why the raw query is a bad search key

Embedding the user's literal words assumes the user phrased the question the way the document phrased the answer. They almost never do.

Users write short, lexically thin queries. "covid policy", "refund", "how do I cancel". Your documents are written by someone else, months earlier, with different vocabulary and full context. The embedding of "how do I cancel" lands in a neighborhood crowded with every cancellation in the corpus. The single relevant chunk is in there, but it is not at the top, and your top-k cut throws it away.

Rewriting fixes the mismatch on the query side, where it is cheap, instead of the index side, where it is not. You are reshaping the search key so it lands closer to the answer.

Multi-query expansion

The idea: one query is one shot at the index. Generate several phrasings of the same intent, search with each, then merge the results. More phrasings means more lexical and semantic surface area, which means a higher chance one of them lands near the right chunk.

You ask the LLM for a handful of variants, run each as its own search, and fuse the rankings with reciprocal rank fusion. RRF rewards documents that several variants agree on, so a chunk that shows up in three of four searches floats to the top even if no single search ranked it first.

from collections import defaultdict
from openai import OpenAI

client = OpenAI()

# vector_search(query, k) -> list[doc_id]
# Your index of choice (pgvector, Qdrant, etc.).

MULTIQ_PROMPT = """Generate 4 alternative phrasings of the
user's query. Vary the vocabulary and specificity. Each must
stand alone (no pronouns, no "this", no "above").
Return one per line, no numbering."""


def expand(query: str) -> list[str]:
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": MULTIQ_PROMPT},
            {"role": "user", "content": query},
        ],
        temperature=0.4,
    )
    content = resp.choices[0].message.content or ""
    lines = content.split("\n")
    variants = [l.strip() for l in lines if l.strip()]
    return [query] + variants  # keep the original


def rrf(rankings: list[list[str]], k: int = 60) -> list[str]:
    scores: dict[str, float] = defaultdict(float)
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking):
            scores[doc_id] += 1.0 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)


def retrieve_multi_query(query: str, k: int = 10) -> list[str]:
    variants = expand(query)
    rankings = [vector_search(v, k=50) for v in variants]
    return rrf(rankings)[:k]

Two details decide whether this helps or just burns tokens. Always keep the original query in the set; the LLM sometimes drifts and the original is your anchor. And use RRF, not a union-and-dedupe. A plain union throws away rank order, which is the only signal that tells you which agreed-upon document to trust.

Multi-query earns its keep on vague and concept-style queries, the ones where the user's intent is fuzzy and a few rephrasings explore it. The variants run in parallel, so the latency cost is one LLM call plus the slowest of N searches, not N searches end to end.

Step-back rewriting

Step-back goes the other direction. Instead of more variants of the same question, you ask the LLM to back up one level of abstraction and pose the broader question first.

The technique comes from a 2023 Google DeepMind paper, Take a Step Back, which found that prompting a model to reason about a general principle before the specific question improved its answers on reasoning benchmarks. The same move helps retrieval. A narrow query like "what is the late-payment penalty for tier 3 enterprise accounts" is so specific that the matching chunk has to contain almost those exact words. The step-back version, "how does billing handle late payments across account tiers", retrieves the policy section that actually defines the penalty in context.

STEP_BACK_PROMPT = """Given a specific user question, write the
broader, more general question whose answer would contain the
context needed to answer the specific one. Return only the
general question, nothing else."""


def step_back(query: str) -> str:
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": STEP_BACK_PROMPT},
            {"role": "user", "content": query},
        ],
        temperature=0.0,
    )
    return resp.choices[0].message.content.strip()


def retrieve_step_back(query: str, k: int = 10) -> list[str]:
    broad = step_back(query)
    specific_hits = vector_search(query, k=k)
    broad_hits = vector_search(broad, k=k)
    return rrf([specific_hits, broad_hits])[:k]

Notice the retrieve function searches with both the original and the step-back query and fuses them. You want the broad context chunk and the specific chunk if it exists. The step-back query pulls in the section that frames the answer; the original pulls in the exact match when there is one. Together they give the model the clause plus the context it sits in.

Step-back shines on narrow, jargon-heavy queries against structured documents: contracts, policy manuals, technical specs. The places where the answer needs surrounding context to mean anything.

What the rewrite actually buys you

Published numbers from the source work and from RAG eval surveys give a consistent shape, not a single magic figure. The step-back paper reported double-digit accuracy gains on reasoning tasks. Multi-query expansion with RRF is a long-standing recall improvement in IR literature, with the size of the gain depending heavily on how thin the original queries are.

The honest framing: rewriting moves recall most when your queries are short, vague, or written in different vocabulary than your corpus. It moves recall least when queries are already long, specific, and lexically close to the documents. If your users paste full sentences that mirror your docs, you may see almost nothing. If they type three words into a search box, the gain can be large. You will not know which case you are in until you measure it on your own query log.

That measurement is the part most teams skip, and it is why they argue about rewriters in the abstract. Pull 200 real queries, label the gold documents by hand, and run recall@10 with and without the rewrite. The week of labeling pays for itself the first time it stops you from shipping a rewriter that does nothing for your traffic.

The latency you are trading for it

Recall is half the decision. The other half is the LLM call you just added to the hot path.

Approach LLM calls p50 add Searches
No rewrite 0 0 ms 1
Multi-query (4) 1 ~300 ms 5, parallel
Step-back 1 ~280 ms 2, parallel

The rewrite is one extra LLM round trip, typically 250 to 350 ms on a small model like gpt-4o-mini. The added searches run in parallel, so they cost you the slowest one, not their sum. For an interactive chatbot that already waits on a generation call, 300 ms of rewrite is usually invisible next to the seconds the answer takes to stream. For a high-QPS, low-latency search box, 300 ms is a lot, and you should test whether a reranker on raw candidates closes the same gap for less.

Three ways to keep the cost down:

  • Cache rewrites. Popular queries repeat. A keyed cache on the rewrite output removes the LLM call entirely for the common case.
  • Gate on query length. Skip the rewrite when the query is already long and specific. Short queries are where the win lives.
  • Use the smallest model that holds quality. Rewriting is a narrow task. A mini model usually matches a frontier model on it for a fraction of the latency.

A pragmatic default

If you ship one rewriter, ship multi-query expansion with RRF, gated on query length, with a rewrite cache. It almost never makes recall worse, the parallel searches keep latency bounded, and the cache cuts the steady-state cost to near zero. Add step-back when your corpus is structured and your queries are narrow.

Then measure. The rewrite that helps your traffic is an empirical question, not a default someone on Reddit picked for a different corpus. Build the 200-query eval once, run it on every change, and you can swap rewriters without guessing.

The team in the opening still ships the bot that quotes the wrong cancellation. The fix was one LLM call in front of the index they already had.

If this was useful

Query rewriting is the front of a longer pipeline. The RAG Pocket Guide covers it alongside the chunking, hybrid retrieval, and reranking patterns that decide what your rewritten query actually finds — with the eval methodology to tell whether any of it moved recall on your corpus. If you are tuning retrieval and want one mental model instead of a stack of blog posts, that is what it is for.

RAG Pocket Guide