← 返回首页 ❓ 面试题库
📑 本篇章节导航 (共7章,点击直达)
一、RAG进阶总览二、检索优化三、GraphRAG四、Agentic RAG五、评估与优化六、面试高频综合题面试速记口诀

Q103 RAG进阶与GraphRAG-Agentic RAG实战

20K Java+AI 岗位2025-2026最热考点 — RAG已从基础版演进到GraphRAG和Agentic RAG。覆盖16种RAG方案对比、混合检索优化、GraphRAG知识图谱增强、Agentic RAG自主检索、Java工程师落地实践。

一、RAG进阶总览

1. RAG的16种演进方案?

类型方案特点适用场景
Naive RAG基础检索+生成简单但效果一般入门
Retrieve-and-Rerank检索+重排序精度提升通用
Hybrid Search向量+BM25取长补短关键词+语义
HyDE假设文档增强提升检索相关性复杂问题
Multi-Query多查询扩展召回更全面歧义问题
Self-RAG自我反思检索质量更高高精度要求
Corrective RAG纠正性检索自动修正容错场景
Parent-Child父子文档索引上下文完整长文档
GraphRAG知识图谱增强关系推理复杂关联
Agentic RAGAgent自主检索灵活智能复杂任务
Modular RAG模块化管道可插拔企业级
CRAG纠正RAG网页搜索补充知识不全
Adaptive RAG自适应检索动态策略混合场景
FLARE主动检索按需检索长文本生成
RichRAG多维检索表格+图片多模态
Real-time RAG实时更新数据新鲜实时场景

2. Naive RAG的三大问题?

1. 检索质量差:召回的文档不相关或不完整

2. 生成幻觉:LLM基于不相关的上下文生成错误答案

3. 缺乏引用:无法追溯到源文档

进阶方向:检索优化(混合/重排序)→ 生成优化(Self-RAG)→ 架构升级(GraphRAG/Agentic)


二、检索优化

3. 混合检索(Hybrid Search)原理?

向量检索擅长语义相似但可能漏掉精确关键词,BM25擅长关键词匹配但不懂语义。混合检索融合两者优势。

融合算法 — 倒数排名融合(RRF):


RRF_score(d) = Σ 1 / (k + rank_i(d))

其中k是常数(通常60),rank_i是文档在第i个检索系统中的排名。


// Java实现RRF
public List<Document> hybridSearch(String query, int topK) {
    List<Document> vectorResults = vectorStore.search(query, topK * 3);  // 向量粗筛
    List<Document> keywordResults = elasticsearch.search(query, topK * 3); // 关键词粗筛

    // RRF融合
    Map<String, Double> scores = new HashMap<>();
    int k = 60;
    for (int i = 0; i < vectorResults.size(); i++) {
        String id = vectorResults.get(i).getId();
        scores.merge(id, 1.0 / (k + i + 1), Double::sum);
    }
    for (int i = 0; i < keywordResults.size(); i++) {
        String id = keywordResults.get(i).getId();
        scores.merge(id, 1.0 / (k + i + 1), Double::sum);
    }

    return scores.entrySet().stream()
        .sorted(Map.Entry.<String, Double>comparingByValue().reversed())
        .limit(topK)
        .map(e -> findById(e.getKey()))
        .collect(Collectors.toList());
}

4. Rerank重排序模型?

先粗筛Top-K,再用Cross-Encoder精排Top-N。

粗筛(Bi-Encoder):Query和Document分别编码,计算余弦相似度。速度快但精度一般。

精排(Cross-Encoder):Query和Document拼接后一起编码,输出相关性分数。精度高但速度慢。

Java集成:


// 使用Cohere Rerank API(Spring AI)
List<Document> reranked = reranker.rerank(query, candidates, 5);
// 或本地模型(BGE-Reranker通过ONNX Runtime)

5. HyDE(Hypothetical Document Embedding)?

原理:先让LLM生成一个"假设性回答",用这个回答的Embedding去检索。


public String hydeSearch(String question) {
    // 1. LLM生成假设性回答
    String hypotheticalAnswer = chatClient.prompt()
        .user("请简要回答以下问题:\n" + question)
        .call().content();

    // 2. 用假设回答的Embedding检索(而非原问题的Embedding)
    List<Document> docs = vectorStore.search(hypotheticalAnswer, 5);

    // 3. 用检索到的文档回答原问题
    return generateAnswer(question, docs);
}

为什么有效?假设性回答和真实文档的语义空间更接近,比用短问题直接检索效果更好。

6. Multi-Query多查询扩展?

将一个复杂问题拆解为多个子问题,分别检索后合并结果。


public List<Document> multiQuerySearch(String question) {
    // 1. LLM生成多个查询变体
    String prompt = "为以下问题生成3个不同角度的搜索查询:\n" + question;
    List<String> queries = chatClient.prompt().user(prompt).call()
        .content().lines().limit(3).collect(Collectors.toList());

    // 2. 分别检索
    List<Document> allDocs = new ArrayList<>();
    for (String q : queries) {
        allDocs.addAll(vectorStore.search(q, 5));
    }

    // 3. 去重 + Rerank
    List<Document> unique = deduplicate(allDocs);
    return reranker.rerank(question, unique, 10);
}

7. 父子文档索引(Parent-Child Index)?

问题:小块检索精度高但上下文不完整。

方案:小块检索,返回大块上下文。


// 存储时建立父子关系
public void indexDocument(Document doc) {
    List<Document> parentChunks = splitBySection(doc, 2000);  // 大块(父)
    for (Document parent : parentChunks) {
        String parentId = UUID.randomUUID().toString();
        parent.getMetadata().put("id", parentId);
        vectorStore.add(parent);  // 存大块

        List<Document> childChunks = split(parent, 500);  // 小块(子)
        for (Document child : childChunks) {
            child.getMetadata().put("parentId", parentId);  // 关联父ID
            vectorStore.add(child);  // 存小块
        }
    }
}

// 检索时:搜小块 → 返回大块
public List<Document> search(String query) {
    List<Document> childHits = vectorStore.search(query, 5);  // 搜小块
    Set<String> parentIds = childHits.stream()
        .map(d -> d.getMetadata().get("parentId").toString())
        .collect(Collectors.toSet());
    return parentIds.stream()
        .map(id -> vectorStore.getById(id))  // 返回大块
        .collect(Collectors.toList());
}

三、GraphRAG

8. GraphRAG是什么?和传统RAG有什么区别?

传统RAG:文档切块 → 向量检索 → 拼接上下文 → LLM生成

GraphRAG:文档 → 抽取实体和关系 → 构建知识图谱 → 图检索+向量检索 → LLM生成

维度传统RAGGraphRAG
知识表示文本块实体+关系
检索方式向量相似度图遍历+向量
关系推理弱强
多跳问题差好
适用场景问答关联分析、推理

9. GraphRAG的架构?


离线阶段:
文档 → LLM抽取实体/关系 → 知识图谱(Neo4j) + 向量库
     → 社区检测 → 社区摘要

在线阶段:
用户问题 → 实体识别 → 图检索(1-2跳邻居)→ 向量检索
        → 融合上下文 → LLM生成 → 带引用回答

10. 知识图谱怎么构建?


// 使用LLM从文本中抽取实体和关系
public List<Triple> extractKnowledge(String text) {
    String prompt = """
        从以下文本中抽取实体和关系,返回JSON数组:
        [{"subject": "实体1", "relation": "关系", "object": "实体2"}]

        文本:%s
        """.formatted(text);

    String json = chatClient.prompt().user(prompt).call().content();
    return parseTriples(json);
}

// 存入Neo4j
public void saveToGraph(List<Triple> triples) {
    for (Triple t : triples) {
        neo4jClient.query(
            "MERGE (s:Entity {name: $subject}) " +
            "MERGE (o:Entity {name: $object}) " +
            "MERGE (s)-[r:RELATES {type: $relation}]->(o)"
        )
        .bind(t.getSubject()).to("subject")
        .bind(t.getObject()).to("object")
        .bind(t.getRelation()).to("relation")
        .run();
    }
}

11. GraphRAG的检索策略?

局部检索:从问题中识别实体 → 查找1-2跳邻居 → 获取相关文本

全局检索:利用社区摘要 → 匹配相关社区 → 获取社区级信息

混合检索:图遍历 + 向量检索融合


public String graphRAGQuery(String question) {
    // 1. 从问题中识别实体
    List<String> entities = extractEntities(question);

    // 2. 图遍历获取相关子图
    StringBuilder graphContext = new StringBuilder();
    for (String entity : entities) {
        List<String> neighbors = neo4jClient.query(
            "MATCH (e:Entity {name: $name})-[r]-(n) " +
            "RETURN n.name + ' - ' + type(r) AS fact LIMIT 20"
        ).bind(entity).to("name").run();

        graphContext.append(String.join("\n", neighbors));
    }

    // 3. 向量检索补充
    List<Document> vectorDocs = vectorStore.search(question, 5);
    String vectorContext = vectorDocs.stream()
        .map(Document::getContent).collect(Collectors.joining("\n"));

    // 4. 融合生成
    return chatClient.prompt()
        .user("基于以下知识图谱和文档回答问题。\n" +
              "知识图谱:\n" + graphContext +
              "\n文档:\n" + vectorContext +
              "\n问题:" + question)
        .call().content();
}

12. GraphRAG的社区检测和摘要?

Microsoft的GraphRAG方案使用Leiden算法做社区检测:

1. 构建知识图谱

2. 运行社区检测算法(Leiden/Louvain)

3. LLM为每个社区生成摘要

4. 查询时先匹配社区,再在社区内检索

Java实现:Neo4j GDS库 + LLM摘要。


四、Agentic RAG

13. Agentic RAG是什么?

传统RAG是固定的"检索→生成"管道,Agentic RAG让Agent自主决定何时检索、检索什么、是否需要多轮检索。

核心能力:

14. Agentic RAG的架构?


用户问题 → Agent(LLM + RAG工具 + 判断能力)
              ↓
         [分析问题]
              ↓
         需要检索?→ No → 直接回答
              ↓ Yes
         [生成查询] → RAG检索
              ↓
         结果足够?→ No → [重新检索/换策略]
              ↓ Yes
         [生成回答]
              ↓
         [自我评估] → 不满意 → [补充检索]
              ↓
         最终答案(带引用)

15. Agentic RAG的Java实现?


@Service
public class AgenticRAGService {
    @Autowired ChatClient chatClient;
    @Autowired VectorStore vectorStore;
    @Autowired WebSearchTool webSearchTool;

    public String query(String question) {
        int maxIterations = 5;
        String context = "";
        String currentQuery = question;

        for (int i = 0; i < maxIterations; i++) {
            // 1. 尝试用当前上下文回答
            String answer = chatClient.prompt()
                .system("你是一个知识助手。基于上下文回答问题。如果上下文不足以回答,回复'NEED_MORE_INFO: 具体需要什么信息'。")
                .user("上下文:\n" + context + "\n\n问题:" + currentQuery)
                .call().content();

            // 2. 检查是否需要更多信息
            if (!answer.startsWith("NEED_MORE_INFO")) {
                return answer;  // 回答满意
            }

            // 3. 生成更好的检索查询
            String searchQuery = answer.replace("NEED_MORE_INFO:", "").trim();

            // 4. 多策略检索
            List<Document> docs = vectorStore.search(searchQuery, 5);
            if (docs.isEmpty()) {
                // 向量库没有,尝试网页搜索
                String webResult = webSearchTool.search(searchQuery);
                context += "\n" + webResult;
            } else {
                context += "\n" + docs.stream().map(Document::getContent)
                    .collect(Collectors.joining("\n"));
            }

            currentQuery = searchQuery;
        }

        return "抱歉,经过多轮检索仍无法找到完整答案。";
    }
}

16. Self-RAG vs Corrective RAG vs Agentic RAG?

方案核心思想自主性
Self-RAGLLM自我评估答案质量,决定是否重新检索中
Corrective RAG检索结果质量差时切换到网页搜索中
Agentic RAGAgent完全自主控制检索策略和流程高

五、评估与优化

17. RAG系统的评估指标?

检索质量:

生成质量:

端到端:

18. RAG优化决策树?


检索不准?
├── Query优化 → Multi-Query / HyDE / Query改写
├── 检索策略 → 混合检索 / Rerank
├── 分块策略 → 调整Chunk Size / 父子文档
└── Embedding → 换更好的模型

幻觉问题?
├── Prompt优化 → 强调"仅基于上下文"
├── 引用标注 → 要求标注来源段落
├── 答案校验 → Self-RAG自我评估
└── 降级 → 回答"根据已有信息无法回答"

延迟高?
├── 减少Top-K → 5→3
├── 缓存 → 语义缓存
├── 异步 → 流式输出
└── 简化 → 去掉Rerank

六、面试高频综合题

19. Java工程师如何落地GraphRAG?


技术栈:Spring AI + Neo4j + Milvus + OpenAI

1. 文档处理:Spring AI ETL Pipeline(DocumentReader → TextSplitter → Embedding)
2. 知识图谱:Neo4j存储实体关系,Spring Data Neo4j操作
3. 向量存储:Milvus存储文档Embedding
4. 检索服务:Neo4j图遍历 + Milvus向量检索融合
5. LLM:OpenAI GPT-4o做抽取、生成、评估

20. RAG vs GraphRAG vs Fine-tuning怎么选?

维度RAGGraphRAGFine-tuning
知识更新实时实时需重训
关系推理弱强中
实现成本低高高
适用场景文档问答关联推理风格定制

建议:先RAG → 效果不够加GraphRAG → 风格定制加Fine-tuning。

21. 如何向面试官展示RAG经验?

"我基于Spring AI构建了企业知识库系统。初期用Naive RAG,准确率只有65%。通过三层优化提升到92%:第一层引入混合检索(向量+BM25),用RRF算法融合;第二层加Rerank(BGE-Reranker),Top5精度提升20%;第三层实现Multi-Query扩展,召回率从70%提升到88%。最近在探索GraphRAG方向,用Neo4j做实体关系抽取,解决多跳推理问题。"


面试速记口诀

RAG优化三阶段:检索优化(混合+重排)→ 生成优化(Self-RAG)→ 架构升级(GraphRAG/Agentic)

>

检索四招:混合检索取长补短、Rerank精排提精度、HyDE增强查询、Multi-Query扩展召回

>

GraphRAG三步:抽取实体关系 → 构建知识图谱 → 图遍历+向量融合

>

Agentic RAG核心:Agent自主判断→动态检索→自我评估→循环直到满意