Multi Query Retrieval

What is Multi-Query Retrieval

Multi-Query Retrieval is a technique where you take one user question, ask an LLM to generate 3-5 different rephrasings of that question, then run all of them (including the original) in parallel against your vector database, and finally merge all the results.

CN: Multi-Query Retrieval(多查询检索)是一种技术:你把用户的一个问题,交给LLM生成3-5个不同的改写版本,然后把所有这些版本(包括原始问题)并行地对向量数据库做检索,最后把所有结果合并起来。

Imagine you’re a detective trying to find a file in a massive archive. Instead of asking the archivist just one question (“Show me files about ‘the big project'”), you ask 5 different versions:

  • “Show me files about ‘the big project'”
  • “Give me documents related to ‘Project Alpha'”
  • “Find me records about ‘the Q4 initiative'”
  • “Show me anything about ‘the CEO’s pet project'”
  • “Find me files mentioning ‘the 2024 rollout'”

Each phrasing might find different documents because the archivist’s index uses different keywords. By combining all results, you’re much more likely to find everything relevant.

CN — 人话比喻
想象你是一个侦探,要在巨大的档案库里找一份文件。你不是只问档案管理员一个问题(”给我看看关于’大项目’的文件”),而是问5个不同版本:

  • “给我看看关于’大项目’的文件”
  • “给我’Project Alpha’相关的文档”
  • “找一下’Q4 计划’的记录”
  • “给我看任何关于’CEO的宠儿项目’的资料”
  • “找提到’2024 年发布’的文件”

因为档案管理员的索引用的是不同的关键词,每个问法都可能找到不同的文件。把所有结果合并起来,你就更可能找到所有相关的东西。

The Three-Stage Process

Multi-Query Retrieval follows three distinct stages,

Stage 1: Query Expansion(查询扩展)

EN: An LLM takes the original user query and generates 3 to 5 semantically diverse reformulations. Each variant captures a different angle, synonym set, or level of specificity.

CN: LLM 接收用户的原始查询,生成3到5个语义多样的改写版本。每个变体捕捉不同的角度、同义词集合或粒度级别。

Example, Original asking “What causes high latency in microservices?”

  1. Variant 1: “How to debug slow response times in distributed systems”
  2. Variant 2: “Network bottlenecks in service-to-service communication”
  3. Variant 3: “Performance optimization for microservice architectures”

Stage 2: Parallel Retrieval

Each variant query is embedded independently and used to search the vector store, producing separate ranked result sets. The original query is typically included as one of the search queries as well.

CN: 每个变体查询被独立地向量化,用来搜索向量数据库,产生各自独立的排序结果集。原始查询通常也被包含在检索查询中。

Stage 3: Result Fusion

(结果融合)

The system merges these result sets, removes duplicates, and produces a unified ranked list. The most common fusion method is Reciprocal Rank Fusion (RRF).

CN: 系统合并这些结果集,去除重复,产生一个统一的排序列表。最常用的融合方法是 Reciprocal Rank Fusion (RRF)

Reciprocal Rank Fusion (RRF)

融合算法

RRF scores each document with the formula:

RRF(d) = Σᵢ 1 / (k + rankᵢ(d))

rankᵢ(d) is the rank of document d in the result set from query i (1-indexed)
rankᵢ(d) 是文档 d 在第 i 个查询结果中的排名(从1开始)
k is a constant (typically 60) that dampens the influence of high ranks
K 是一个常数(通常为60),用于削弱高排名的影响

example

Let’s say we have 2 user questions (variants) that we searched against our vector database. We’ll track Document A and Document B across these two search result lists.

CN: 假设我们有2个用户问题(变体)对向量数据库进行了检索。我们追踪 文档A 和 文档B 在这两组搜索结果中的表现。

  • Original Question (原始问题): “How to handle errors in Python?”
  • Variant 1 (变体1): “What are the best practices for exception handling in Python?"
  • Variant 2 (变体2): “How do I debug and fix Python runtime errors?”

We have a vector database with 5 documents (text chunks) inside.

CN: 我们的向量数据库里有5个文档(文本块)。

Real Document ID (真实文档ID)Content Snippet (内容片段)
doc_001“Python uses try-except blocks to catch exceptions…”
doc_002“Best practices for exception handling include logging and specific exception types…”
doc_003“Debugging tools like pdb and logging help trace runtime errors…”
doc_004“Data processing pipelines often fail due to missing values…”
doc_005“Unit tests with pytest can catch errors before runtime…”

Step 1: 每个查询被向量化 (Each Query Gets Embedded)

# 伪代码表示 / Pseudo-code representation
embedding_model = OpenAIEmbeddings()

# 生成3个向量 / Generate 3 vectors
vec_original = embedding_model.embed("How to handle errors in Python?")
vec_variant1 = embedding_model.embed("What are the best practices for exception handling in Python?")
vec_variant2 = embedding_model.embed("How do I debug and fix Python runtime errors?")

# 每个vec都是 [0.123, -0.456, 0.789, ...] 这样的浮点数列表 (1536个)
# Each vec is a list of floats like [0.123, -0.456, 0.789, ...] (1536 of them)

Step 2: 每个向量独立检索 (Each Vector Searches Independently)

 Each vector is sent to the vector database (e.g., Chroma, Pinecone, Milvus). The database computes cosine similarity between the query vector and ALL document vectors in the store, then returns the top K (e.g., top 3) most similar documents.

CN: 每个向量被发送到向量数据库(如 Chroma、Pinecone、Milvus)。数据库计算查询向量和库中所有文档向量之间的余弦相似度,然后返回最相似的 Top K(比如 Top 3)个文档。

 Query 1 (Original) Results:

CN — 查询1 (原始) 返回结果:

Rank (排名)Document IDSimilarity Score (相似度)Content (内容)
1doc_0010.92“Python uses try-except blocks to catch exceptions…”
2doc_0020.85“Best practices for exception handling include…”
3doc_0050.72“Unit tests with pytest can catch errors…”

Query 2 (Variant 1) Results:

CN — 查询2 (变体1) 返回结果:

Rank (排名)Document IDSimilarity Score (相似度)Content (内容)
1doc_0020.95“Best practices for exception handling include…”
2doc_0010.88“Python uses try-except blocks to catch exceptions…”
3doc_0030.70“Debugging tools like pdb and logging…”

Here, doc_002 is now “Document B” (but it’s the same physical chunk as before). doc_001 is “Document A”. A new one, doc_003, appears as “Document C”.

CN: 这里,doc_002 现在成了”文档B”(但它是和之前一样的物理块)。doc_001 是”文档A”。一个新的 doc_003 出现了,作为”文档C”。

Query 3 (Variant 2) Results:

CN — 查询3 (变体2) 返回结果:

Rank (排名)Document IDSimilarity Score (相似度)Content (内容)
1doc_0030.91“Debugging tools like pdb and logging…”
2doc_0010.80“Python uses try-except blocks to catch exceptions…”
3doc_0040.65“Data processing pipelines often fail…”

Step 3: RRF 融合 — 将 “A/B/C” 映射回真实ID (RRF Fusion — Mapping A/B/C Back to Real IDs)

 Now, let’s build the RRF table using real doc_001doc_002, etc.

CN: 现在,我们用真实的 doc_001doc_002 等来构建 RRF 表格。

真实文档ID (Real ID)Q1 (Original) RankQ2 (Variant 1) RankQ3 (Variant 2) RankRRF 计算 (Calculation)最终分数 (Final Score)
doc_0011221/61 + 1/62 + 1/62 = 0.016393 + 0.016129 + 0.016129 = 0.048651
doc_00221— (未出现)1/62 + 1/61 + 0 = 0.016129 + 0.016393 = 0.032522
doc_003— (未出现)310 + 1/63 + 1/61 = 0.015873 + 0.016393 = 0.032266
doc_00531/63 + 0 + 0 = 0.015873
doc_00430 + 0 + 1/63 = 0.015873

 Final ranking after RRF: doc_001 (1st) > doc_002 (2nd) > doc_003 (3rd).

CN: RRF 后的最终排名:doc_001 (第1) > doc_002 (第2) > doc_003 (第3)

Key Takeaways

要点 (Topic)ENCN
核心思想Generate multiple query reformulations from one user question从一个用户问题生成多个查询改写版本
三步流程Query Expansion → Parallel Retrieval → Result Fusion查询扩展 → 并行检索 → 结果融合
LLM的作用LLM generates diverse query variants covering different anglesLLM生成覆盖不同角度的多样化查询变体
并行检索Each variant is embedded and searched independently每个变体被独立向量化并搜索
结果融合RRF (Reciprocal Rank Fusion) merges ranked results without score normalizationRRF(倒数排名融合)无需分数归一化即可合并排序结果
RRF公式RRF(d) = Σᵢ 1/(k + rankᵢ(d)), k=60 typicallyRRF(d) = Σᵢ 1/(k + rankᵢ(d)),k通常为60
主要收益Overcomes single-point-of-failure in retrieval; improves recall克服检索中的单点故障;提高召回率
适用场景Complex questions, vocabulary mismatch, discovery tasks复杂问题、词汇不匹配、探索性任务
LangChain实现MultiQueryRetriever.from_llm(retriever, llm)MultiQueryRetriever.from_llm(retriever, llm)
include_originalWhether to include original query in the retrieval set是否在检索集中包含原始查询
去重Unique union of all retrieved documents所有检索文档的唯一并集
与HyDE的区别Multi-Query generates reformulations; HyDE generates a hypothetical answer documentMulti-Query生成改写;HyDE生成假设答案文档

RAG 2.0

RAG (Retrieval-Augmented Generation) is an AI architecture that retrieves relevant information from external knowledge sources and provides it to an LLM, enabling the model to generate accurate, up-to-date, and context-aware responses.

LLM = Answer from Training
while
RAG = Search First + Then Answer

What is RAG 2.0? There is no official industry standard that defines “RAG 1.0”, “RAG 2.0”, or “RAG 3.0”.

The concept of “RAG 2.0”, known as Agentic RAG, represents a shift from a “simple data retrieval plugin” to a “deeply integrated, agentic system with reasoning capabilities.” The industry has indeed evolved from 1.0 and is now progressing toward 3.0.

Simplest Way to Remember

VersionMeaning
RAG 1.0Search Once
RAG 2.0Search + Reason
RAG 3.0
(coming ? on the way?)
Agent + Search + Tools + Workflow
RAG Foundation: Embedding

Embedding is a fundamental technology in machine learning and natural language processing that transforms discrete or complex objects (such as words, sentences, or images) into numerical vector representations of a fixed dimension

more …

RAG Foundation: RAG Pipeline

A simple RAG pipeline has two phases and five stages

  • Phase 1: Indexing (Offline / 离线阶段)
    Build the searchable knowledge base before users ask questions.
    离线阶段(索引):先把所有文档加载进来,切分成小块,调用 Embedding 模型转成向量,最后存进 FAISS 等向量数据库里。
  • Phase 2: Retrieval & Generation (Online / 在线阶段)
    Execute at query time for each user question.
    在线阶段(检索+生成):用户提问时,先把问题也转成向量,去库里找最相似的 Top-K 个块,把这几个块作为“参考资料”连同问题一起扔给 GPT,让它写出最终回答。

more …

In AI, a chunking strategy is the method used to break down large pieces of information—like long documents, complex prompts, or even audio and video—into smaller, more manageable segments called “chunks”. These chunks are the fundamental units that AI systems, especially Large Language Models (LLMs), work with to understand, process, and retrieve information efficiently.

Common Chunking Strategies

The best strategy depends on the type of data and the specific task. Here are the most common approaches:

StrategyDescriptionBest For
Fixed-Size ChunkingSplits text into chunks of a predetermined size (e.g., a specific number of words, characters, or tokens). Often uses a “sliding window” with overlap to preserve context across boundaries.Simple implementation; works well when document structure is uniform and not critical.
Semantic ChunkingGroups text based on meaning, using algorithms to find natural topic boundaries and keep related ideas together.Maintaining the coherence of ideas within each chunk for better understanding.
Structure-Aware ChunkingRespects the natural format of the document, splitting at points like paragraphs, sentences, or headers.Documents with clear structure (e.g., articles, reports, code) where breaking mid-section would lose meaning.
Recursive ChunkingStarts with large chunks and recursively splits them into smaller ones until they meet a target size, trying to respect natural boundaries like paragraphs or sentences.A balanced approach that aims to create the largest possible meaningful chunks.
Multimodal ChunkingExtends the concept to non-text data, such as segmenting audio by silences, video by scene changes, or identifying objects within images.AI systems that process images, audio, and video, not just text
Chunking Strategy: Recursive Chunking

Recursive Chunking is a hierarchical text splitting strategy that uses a priority list of separators (e.g., ["\n\n", "\n", " ", """]), starting with the highest-level (semantically strongest) separator. If a chunk still exceeds the chunk_size limit after splitting, it recursively applies the next-level separator to that chunk, continuing until all chunks meet the size requirement.

more …

Chunking Strategy: Semantic Chunking

Semantic Chunking is a strategy for splitting documents into smaller pieces (chunks) based on meaning, rather than on fixed character counts or simple separators. It tries to keep sentences or paragraphs that are about the same topic together, and split where the topic changes. Think of it as “a smart editor who knows where one idea ends and the next begins

more …

Chunking Strategy: Parent-Child Retrieval

Parent-Child Retrieval (also known as Small-to-Big Retrieval) is a two-tier hierarchical indexing strategy.

more …


Hybrid Search refers to a search technique that combines multiple search algorithms simultaneously to retrieve the most relevant results. It most commonly merges Lexical (Keyword) Search with Semantic (Vector/Dense) Search.
基于关键词的搜索(词汇搜索)与基于语义的搜索(向量/稠密搜索)

  1. Lexical Search (Sparse Retrieval): Typically powered by algorithms like BM25 or TF-IDF. It relies on exact keyword matching and statistical term frequency. It excels at finding specific proper nouns, IDs, or rare terminology (e.g., “error code 404”).
    词汇搜索(稀疏检索): 通常由 BM25 或 TF-IDF 等算法驱动。它依赖于精确的关键词匹配和统计词频。它在查找特定的专有名词、ID 或罕见术语时表现出色(例如:“错误代码 404”)。
  2. Semantic Search (Dense Retrieval): Powered by embedding models (e.g., Sentence-BERT). It converts text into high-dimensional vectors and retrieves documents based on “meaning” rather than exact words. It excels at understanding synonyms, context, and natural language queries (e.g., “How to fix a broken internet connection”).
    语义搜索(稠密检索): 由嵌入模型(如 Sentence-BERT)驱动。它将文本转换为高维向量,并根据“含义”而非精确词汇来检索文档。它在理解同义词、上下文和自然语言查询(例如:“如何修复断开的网络连接”)方面表现出色。
BM25 (keyword-based search)

BM25 (Best Matching 25) is a keyword-based ranking algorithm used in information retrieval to score and rank documents based on their relevance to a search query. It’s called “Best Matching 25” because it was the 25th variant in a series of scoring functions proposed by its creators. BM25 is the default ranking algorithm in Elasticsearch and most production search engines

more …

RRF

RRF stands for Reciprocal Rank Fusion. It is an algorithm that merges multiple ranked result lists from different search systems into a single unified ranking.
全称是 Reciprocal Rank Fusion(倒数排名融合)。它是一种将来自不同检索系统的多个排名结果列表合并成一个统一排名的算法.

more …

Vector Database Selection

Compare normal DB, such as SQL DB, MySQL, PostgreSQL, They fundamental difference is what they search for and how they find it. A traditional SQL database (like MySQL, PostgreSQL without pgvector) is built for exact matching and structured queries. It answers questions like: “Find the customer with ID = 12345” or “Give me all orders over $100.” A Vector Database is built for semantic similarity and unstructured data. It answers questions like: “Find all documents that talk about the same topic as this paragraph” or “Show me products that look visually similar to this image.”

Normal DB vs Vector DB

要点ENCN
核心:精确匹配 vs. 语义相似度Core: Exact matching vs. Semantic similarity核心:精确匹配 vs. 语义相似度
SQL存结构化数据(数字/字符串),Vector存浮点数数组(含义)SQL stores structured data (numbers/strings); Vector stores float arrays (meaning)SQL存结构化数据,Vector存浮点数数组(含义)
SQL查询用WHERE精确条件;Vector查询用ORDER BY距离SQL queries use WHERE exact conditions; Vector queries use ORDER BY distanceSQL查询用WHERE精确条件;Vector查询用ORDER BY距离
SQL用B-Tree/哈希(精确查找);Vector用HNSW/IVF(近似查找)SQL uses B-Tree/Hash (exact lookup); Vector uses HNSW/IVF (approximate)SQL用B-Tree/哈希(精确);Vector用HNSW/IVF(近似)
SQL结果是二元的(匹配/不匹配);Vector结果是排序的(相似度分数)SQL results are binary (match/no match); Vector results are ranked (similarity scores)SQL结果是二元的;Vector结果是排序的
SQL适合事务、财务报表;Vector适合RAG、推荐、AISQL suits transactions, ledgers; Vector suits RAG, recommendations, AISQL适合事务、报表;Vector适合RAG、推荐、AI
专用向量库不能做JOIN和ACID;但pgvector可以在PostgreSQL中兼得Dedicated vector DBs can’t do JOINs/ACID; pgvector lets you have both in PostgreSQL专用向量库不能做JOIN和ACID;pgvector可以让两者兼得
在实际RAG中,两者是互补的,不是替代关系In real-world RAG, they are complementary, not replacements在实际RAG中,两者是互补的,不是替代关系

Vector database selection is the process of choosing the right vector database technology for your AI application from dozens of available options — Milvus, Qdrant, Weaviate, Pinecone, pgvector, Chroma, and more.

Mainstream Vector Database Landscape

CategoryExamplesCN
Fully Managed (PaaS)Pinecone, Zilliz Cloud, Weaviate Cloud全托管云服务
Self-Hosted Open SourceQdrant, Milvus, Weaviate, Chroma自托管开源
Database Extensionspgvector, MongoDB Vector Search, Elasticsearch数据库扩展
Cloud Provider ServicesAzure AI Search, AWS S3 Vectors, Tencent Cloud VDB云厂商服务
Embedded/SpecializedSQLite (vector), LanceDB嵌入式/专用

Detailed Comparison

DatabaseAvg Query TimeCost (1M @ 1536-dim)Best ForCN 最适合
Milvus/Zilliz50.7ms$115/moFastest queries + good flexibility最快查询+灵活性好
Weaviate51.7ms$160/moNative datetime/geo + hybrid search原生时间/地理+混合检索
Qdrant73.1ms$103/moBest balance (speed + flexibility + cost)最佳平衡(速度+灵活性+成本)
Pinecone106.3ms$30/moCheapest (⚠️ poor schema flexibility)最便宜(⚠️ Schema灵活性差)
Chroma275.4ms$139/moEasiest setup + prototyping最简单设置+原型开发

7 Types of Data Stored in VectorDB in AI Projects

类型ENCN更新频率过滤器主要用途
RAG 文档块RAG Document ChunksRAG 文档块source, page问答
用户记忆 (Mem0)User Memory (Mem0)用户记忆 (Mem0)user_id个性化
工具 SchemaTool Schemas工具 Schematool_category工具选择
Agent 轨迹Agent TrajectoriesAgent 轨迹user_id, outcome经验复用
黄金数据集Golden Dataset黄金数据集category评估
语义缓存Semantic Cache语义缓存降本提速
代码索引Code Index代码索引language, path代码生成

Reranker is a sophisticated machine learning model designed to refine and reorder a list of candidate items—such as search results, document passages—to maximize their relevance to a specific query or context.

Reranker(重排序器)是一种复杂的机器学习模型,旨在优化并重新排序候选项目列表(如搜索结果、文档片段),以最大程度提高它们与特定查询或上下文的相关性。

Reranker

Reranker实战


Advanced RAG (Advanced Retrieval-Augmented Generation) is an evolutionary upgrade over the basic “Naive RAG” pipeline. It adds a suite of optimization techniques at every stage of the RAG workflow — pre-retrieval, retrieval, post-retrieval, and evaluation — to systematically improve retrieval precision, recall, and generation quality.

Advanced RAG

Query Rewrite

Multi Query Retrieval

Context Compression