Advanced RAG – Hybrid Search, Query Transformation and Reranking

In production environments, basic (“Naive”) RAG often fails when users submit ambiguous follow-up questions, search for exact product codes or error strings, or retrieve noisy context chunks. Advanced RAG in Spring AI solves these failure modes using a modular pipeline (RetrievalAugmentationAdvisor) that enhances retrieval accuracy across three critical pillars: Query Transformation, Hybrid Search, and Reranking.

1. Advanced RAG Pipeline Architecture

Rather than blindly embedding a raw user string and passing top-$K$ vector matches directly to an LLM, Advanced RAG inserts intelligent optimization stages around the retriever:
  1. Pre-Retrieval (Query Transformation & Expansion): Rewrites, compresses, translates, or expands the user’s raw input into clean, retrieval-ready search queries.

  2. Retrieval (Hybrid Search): Combines dense semantic vector similarity with sparse lexical keyword matching—merged via fusion algorithms—to capture both conceptual intent and exact terms.

  3. Post-Retrieval (Reranking & Filtering): Evaluates the broad candidate pool using a high-precision cross-encoder or LLM judge, reordering chunks by true relevance and discarding low-signal noise before generation.

2. Pillar 1: Query Transformation & Expansion

Users rarely write optimal search queries—they use pronouns from earlier turns, typos, conversational filler, or mismatched terminology. Spring AI provides built-in QueryTransformer and QueryExpander components to repair queries prior to retrieval:
  • Query Rewriting (RewriteQueryTransformer): Uses an LLM to strip conversational noise and rephrase vague or poorly structured user prompts into crisp, keyword-rich search queries tailored for retrieval engines.

  • Conversational Query Compression (CompressionQueryTransformer): Inspects ongoing chat history alongside a context-dependent follow-up question (e.g., “How do I reset it?”) and compresses them into a standalone, self-contained query (e.g., “How do I reset the Spring TransactionManager?”).

  • Query Translation (TranslationQueryTransformer): Translates incoming user queries into the primary language of the indexed enterprise knowledge base so multilingual users can search monolingual document repositories seamlessly.

  • Multi-Query Expansion (MultiQueryExpander): Generates multiple semantic variations or sub-queries from a single complex prompt, executes parallel retrievals across all phrasings, and deduplicates the combined document pool to overcome vocabulary mismatch.

  • Hypothetical Document Embeddings (HyDE): Prompts an LLM to generate a plausible hypothetical answer to the user’s question first, then embeds that hypothetical answer to search the vector store—matching answer-to-answer semantics rather than question-to-answer semantics.

3. Pillar 2: Hybrid Search (Dense + Sparse Retrieval)

Pure vector search excels at conceptual similarity (“authentication failure” matching “login rejected”), but struggles with exact identifiers such as error codes (ERR_504_GATEWAY), SKU numbers, function names, or acronyms. Hybrid Search pairs two complementary retrieval signals:

Retrieval Signal Underlying Mechanism Primary Strengths Primary Weaknesses
Dense Vector Search Embedding models + ANN indexes (HNSW / IVFFlat) Captures synonyms, paraphrasing, and conceptual intent Misses exact alphanumeric IDs, rare jargon, and strict keyword matches
Sparse Lexical Search Full-Text Search / BM25 / TF-IDF (tsvector in Postgres, Lucene/RediSearch) Pinpoints exact product codes, proper nouns, and technical terms Fails when user phrasing uses different words than the document

Fusion Ranking: Reciprocal Rank Fusion (RRF)

Because vector cosine similarity scores and lexical BM25 scores operate on completely incompatible mathematical scales, hybrid pipelines combine them using Reciprocal Rank Fusion (RRF):

  • Each retriever independently ranks its top-$N$ candidate documents.

  • RRF computes a unified score based solely on each document’s rank position across both lists ($\text{Score} = \sum \frac{1}{k + \text{rank}}$), boosting documents that appear high in both semantic and keyword results without requiring fragile score normalization.

  • In Spring AI, hybrid retrieval is implemented either natively via vector stores supporting hybrid queries (such as PostgreSQL combining pgvector with tsvector full-text search, MongoDB Atlas, or Azure AI Search) or by combining multiple DocumentRetriever instances and fusing their results.

4. Pillar 3: Post-Retrieval Reranking

Vector databases rely on bi-encoder models that embed queries and documents independently for speed—trading off deep token-level interaction for sub-second scalability across millions of records. Reranking introduces a second-stage filter using a cross-encoder or specialized reranker model:
  1. Broad Recall Stage: The hybrid retriever fetches a wider candidate pool (e.g., top 20–50 chunks) so the true answer is guaranteed to be captured.

  2. Deep Precision Scoring: A cross-encoder reranker (such as Cohere Rerank, BGE-Reranker, or an LLM-based DocumentPostProcessor) processes the (query, document) pair simultaneously, evaluating fine-grained semantic alignment between every query token and document token.

  3. Truncation & Context Ordering: The pipeline sorts candidates by their new relevance scores, keeps only the top 3–5 highest-scoring chunks, and places the strongest context at the beginning/end of the prompt to mitigate the “Lost in the Middle” LLM attention phenomenon.

5. Production Best Practices & Trade-Offs

  • Manage Latency Budgets Intentionally: Every query transformation LLM call and cross-encoder reranking step adds latency; use lightweight, low-latency models for query rewriting and reserve heavy reranking for high-stakes queries where precision matters most.

  • Over-Fetch Before Reranking: Configure your DocumentRetriever with a higher topK (e.g., 25) when a reranker is attached, then trim down to topK = 5 post-reranking so the final LLM prompt stays compact and cost-efficient.

  • Preserve Source Citations Through Fusion: Ensure document UUIDs and metadata attributes remain intact during query expansion and RRF merging so duplicate chunks are cleanly deduplicated and citations remain accurate.

  • Measure End-to-End Impact: Validate hybrid and reranking changes against golden test datasets using metrics such as Recall@K, Mean Reciprocal Rank (MRR), and Spring AI’s RelevancyEvaluator and FactCheckingEvaluator.

Hands-on Experiment: Enterprise Knowledge Discovery Assistant using Advanced RAG (Hybrid Search, Query Transformation and Reranking)

Aim: To build a Spring Boot application that stores company knowledge articles, finds the best matching articles using Hybrid Search, Query Transformation and Reranking, and answers employee questions with the article titles as sources.

Description: The Enterprise Knowledge Discovery Assistant helps employees find answers in company policies and IT guides (HR, IT, Finance, Security).

  • Add knowledge: Each article is saved in MySQL (for keyword search) and as an embedding in a vector store (for meaning-based search).
  • Query Transformation: The user’s question is rewritten into a clear search query, and 2 more queries with synonyms are created. A casual question like “Can I telecommute?” also searches for “work from home policy”.
  • Hybrid Search: Every query runs two searches: vector search (finds similar meaning) and keyword search in MySQL (finds exact words like error code ERR-4021). The two result lists are merged using Reciprocal Rank Fusion (RRF).
  • Reranking: The LLM reads the question and each candidate article and gives a score from 0 to 10, then the best 3 are kept.
  • Answer: The LLM answers using only these 3 articles and mentions their titles. Every question is saved in search_logs.
  • Switches: hybrid, transform and rerank can be turned on or off in the request, so you can compare a basic search with the advanced one.

Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ IDEA / Eclipse / VS Code), Postman, and an OpenAI API key.

Steps

  1. Generate the project using Spring Initializr
  2. Add dependencies and configure application.properties
  3. Create the entities (KnowledgeArticle, SearchLog) and repositories
  4. Create KnowledgeService to save articles in MySQL and the vector store
  5. Create QueryTransformService (rewrite and multi-query)
  6. Create HybridSearchService (vector search + keyword search + RRF)
  7. Create RerankService (LLM relevance scoring)
  8. Create KnowledgeAssistantService to join all stages and generate the answer
  9. Create the controllers
  10. Run the application and test with Postman

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven | Language: Java | Packaging: Jar | Java: 17
  • Spring Boot: 3.4.x (Spring AI 1.0 needs Spring Boot 3.4 or higher, so 3.3.x will not work)
  • Group: com.example | Artifact: enterprise-knowledge-assistant
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, OpenAI (Spring AI), and spring-ai-vector-store (add manually in pom.xml if it is not listed)

Step 2: Project Structure

enterprise-knowledge-assistant
├── pom.xml
└── src/main
    ├── java/com/example/knowledge
    │   ├── KnowledgeAssistantApplication.java
    │   ├── entity
    │   │   ├── KnowledgeArticle.java
    │   │   └── SearchLog.java
    │   ├── repository
    │   │   ├── KnowledgeArticleRepository.java
    │   │   └── SearchLogRepository.java
    │   ├── service
    │   │   ├── KnowledgeService.java
    │   │   ├── QueryTransformService.java
    │   │   ├── HybridSearchService.java
    │   │   ├── RerankService.java
    │   │   └── KnowledgeAssistantService.java
    │   └── controller
    │       ├── KnowledgeController.java
    │       └── SearchController.java
    └── resources/application.properties

Step 3: Github Link: 

Step 4: Download the application from above github link, then test the below CURD operations

URLs, Request Payloads and Sample Outputs

# Method URL Purpose
1 POST http://localhost:8080/api/knowledge/bulk Load sample articles
2 POST http://localhost:8080/api/knowledge Add one article
3 GET http://localhost:8080/api/knowledge List all articles
4 POST http://localhost:8080/api/search/ask Ask a question
5 GET http://localhost:8080/api/search/logs See the question history

1. Load sample articles: POST /api/knowledge/bulk

json
[
  {
    "title": "Work From Home Policy",
    "department": "HR",
    "content": "Employees may work remotely up to three days a week with manager approval. Remote work requests must be submitted in the HR portal at least two days in advance. Full-time remote roles need director approval."
  },
  {
    "title": "Annual Leave Policy",
    "department": "HR",
    "content": "Every full-time employee receives 24 days of paid annual leave per year. Up to 5 unused days can be carried forward to the next calendar year. Leave must be applied through the HR portal."
  },
  {
    "title": "VPN Troubleshooting",
    "department": "IT",
    "content": "Error ERR-4021 on the corporate VPN means the device certificate has expired. Open the Self Service Portal, choose Renew Certificate, then restart the VPN client. If the problem continues, raise a ticket with the IT Service Desk."
  },
  {
    "title": "Laptop Replacement Policy",
    "department": "IT",
    "content": "Company laptops are replaced every four years. Employees can request an early replacement if the device fails hardware diagnostics. Requests go through the IT Service Desk."
  },
  {
    "title": "Travel Expense Reimbursement",
    "department": "Finance",
    "content": "Travel expenses must be submitted within 30 days of the trip with original receipts. Economy class is mandatory for flights under six hours. The hotel limit is 150 USD per night in metro cities."
  },
  {
    "title": "Information Security Policy",
    "department": "Security",
    "content": "Passwords must be at least 12 characters and changed every 90 days. Multi-factor authentication is mandatory for all corporate applications. Report any suspected phishing email to the security team immediately."
  },
  {
    "title": "New Employee Onboarding",
    "department": "HR",
    "content": "On the first day, new employees collect their laptop and access card from the IT desk and complete the security awareness training within the first week. Payroll forms must be submitted to HR within three days."
  }
]

Sample output (shortened; content of each article is returned too):

json
[
  { "id": 1, "title": "Work From Home Policy", "department": "HR", "createdAt": "2026-11-30T12:15:03" },
  { "id": 2, "title": "Annual Leave Policy", "department": "HR", "createdAt": "2026-11-30T12:15:04" },
  { "id": 3, "title": "VPN Troubleshooting", "department": "IT", "createdAt": "2026-11-30T12:15:04" },
  { "id": 4, "title": "Laptop Replacement Policy", "department": "IT", "createdAt": "2026-11-30T12:15:05" },
  { "id": 5, "title": "Travel Expense Reimbursement", "department": "Finance", "createdAt": "2026-11-30T12:15:05" },
  { "id": 6, "title": "Information Security Policy", "department": "Security", "createdAt": "2026-11-30T12:15:06" },
  { "id": 7, "title": "New Employee Onboarding", "department": "HR", "createdAt": "2026-11-30T12:15:06" }
]

2. Add one article: POST /api/knowledge

json
{
  "title": "Expense Approval Limits",
  "department": "Finance",
  "content": "Managers can approve expenses up to 1000 USD. Expenses above 1000 USD need approval from the finance director."
}

Sample output:

json
{
  "id": 8,
  "title": "Expense Approval Limits",
  "department": "Finance",
  "content": "Managers can approve expenses up to 1000 USD. Expenses above 1000 USD need approval from the finance director.",
  "createdAt": "2026-11-30T12:20:11"
}

3. List all articles: GET /api/knowledge returns the saved articles as a JSON list (same format as above).

4a. Ask a question (all three techniques ON): POST /api/search/ask

This question uses the word “telecommute”, which is not in the article. Vector search and query transformation find it by meaning.

json
{
  "question": "Can I telecommute from home during the week?"
}

Sample output:

json
{
  "question": "Can I telecommute from home during the week?",
  "searchQueries": [
    "Can I telecommute from home during the week?",
    "remote work policy work from home days per week",
    "telecommuting rules for employees",
    "working from home weekly limit approval"
  ],
  "candidatesBeforeRerank": [
    { "id": 1, "title": "Work From Home Policy", "department": "HR", "rrfScore": 0.0984, "rerankScore": 0 },
    { "id": 7, "title": "New Employee Onboarding", "department": "HR", "rrfScore": 0.0306, "rerankScore": 0 },
    { "id": 6, "title": "Information Security Policy", "department": "Security", "rrfScore": 0.0289, "rerankScore": 0 },
    { "id": 2, "title": "Annual Leave Policy", "department": "HR", "rrfScore": 0.0278, "rerankScore": 0 }
  ],
  "finalSources": [
    { "id": 1, "title": "Work From Home Policy", "department": "HR", "rrfScore": 0.0984, "rerankScore": 10 },
    { "id": 2, "title": "Annual Leave Policy", "department": "HR", "rrfScore": 0.0278, "rerankScore": 2 },
    { "id": 7, "title": "New Employee Onboarding", "department": "HR", "rrfScore": 0.0306, "rerankScore": 1 }
  ],
  "answer": "Yes. Employees can work remotely up to three days a week with manager approval [Work From Home Policy]. Requests must be submitted in the HR portal at least two days in advance [Work From Home Policy]."
}

4b. Ask with an exact error code: POST /api/search/ask

Keyword search finds the exact code ERR-4021. The department filter limits the search to IT articles.

json
{
  "question": "My VPN shows ERR-4021, what should I do?",
  "department": "IT"
}

Sample output:

json
{
  "question": "My VPN shows ERR-4021, what should I do?",
  "searchQueries": [
    "My VPN shows ERR-4021, what should I do?",
    "VPN error ERR-4021 fix",
    "VPN ERR-4021 troubleshooting steps",
    "resolve corporate VPN error 4021"
  ],
  "candidatesBeforeRerank": [
    { "id": 3, "title": "VPN Troubleshooting", "department": "IT", "rrfScore": 0.1311, "rerankScore": 0 },
    { "id": 4, "title": "Laptop Replacement Policy", "department": "IT", "rrfScore": 0.0625, "rerankScore": 0 }
  ],
  "finalSources": [
    { "id": 3, "title": "VPN Troubleshooting", "department": "IT", "rrfScore": 0.1311, "rerankScore": 10 },
    { "id": 4, "title": "Laptop Replacement Policy", "department": "IT", "rrfScore": 0.0625, "rerankScore": 0 }
  ],
  "answer": "ERR-4021 means the device certificate has expired [VPN Troubleshooting]. Open the Self Service Portal, choose Renew Certificate, and restart the VPN client [VPN Troubleshooting]. If the problem continues, raise a ticket with the IT Service Desk [VPN Troubleshooting]."
}

4c. Basic search for comparison (all three OFF): POST /api/search/ask

json
{
  "question": "How many vacation days do I get and can I carry them over?",
  "hybrid": false,
  "transform": false,
  "rerank": false
}

Sample output (only one query is used, and the order of results is not corrected by reranking):

json
{
  "question": "How many vacation days do I get and can I carry them over?",
  "searchQueries": [
    "How many vacation days do I get and can I carry them over?"
  ],
  "candidatesBeforeRerank": [
    { "id": 2, "title": "Annual Leave Policy", "department": "HR", "rrfScore": 0.0164, "rerankScore": 0 },
    { "id": 1, "title": "Work From Home Policy", "department": "HR", "rrfScore": 0.0161, "rerankScore": 0 },
    { "id": 7, "title": "New Employee Onboarding", "department": "HR", "rrfScore": 0.0159, "rerankScore": 0 },
    { "id": 5, "title": "Travel Expense Reimbursement", "department": "Finance", "rrfScore": 0.0156, "rerankScore": 0 },
    { "id": 6, "title": "Information Security Policy", "department": "Security", "rrfScore": 0.0154, "rerankScore": 0 }
  ],
  "finalSources": [
    { "id": 2, "title": "Annual Leave Policy", "department": "HR", "rrfScore": 0.0164, "rerankScore": 0 },
    { "id": 1, "title": "Work From Home Policy", "department": "HR", "rrfScore": 0.0161, "rerankScore": 0 },
    { "id": 7, "title": "New Employee Onboarding", "department": "HR", "rrfScore": 0.0159, "rerankScore": 0 }
  ],
  "answer": "Every full-time employee receives 24 days of paid annual leave per year, and up to 5 unused days can be carried forward to the next calendar year [Annual Leave Policy]."
}

Compare the finalSources of 4a and 4c: with rerank ON, irrelevant articles get low scores (0 to 2) and the best article is always first.

5. Question history: GET /api/search/logs

json
[
  {
    "id": 3,
    "question": "How many vacation days do I get and can I carry them over?",
    "searchQueries": "How many vacation days do I get and can I carry them over?",
    "answer": "Every full-time employee receives 24 days of paid annual leave per year...",
    "createdAt": "2026-11-30T12:31:40"
  }
]

Notes

  • The scores and answers above are samples. They will be a little different in your run because the LLM output changes. IDs 1 to 7 are correct only on a fresh database.
  • One question with all three techniques makes about 4 LLM calls (rewrite, variants, rerank, answer) plus 4 embedding calls, so it is slower and costs more than a basic search. Use the switches to compare.
  • Keyword search here uses MySQL LIKE, which is simple and good for learning. For large data, use MySQL FULLTEXT or a search engine.
Scroll to Top