图片预览

滚轮缩放 · 拖动移动 · Esc 关闭

Skip to content

结构化 RAG 向量化与检索系统设计方案 ​

📋 文档信息 ​

  • 文档名称: 结构化RAG向量化与检索系统设计方案
  • 版本: v1.0
  • 日期: 2025-12-15
  • 状态: 设计阶段
  • 作者: AI Architecture Team

📖 目录 ​


1. 项目背景 ​

1.1 当前痛点 ​

问题1: 简单切块破坏语义完整性 ​

原始文档:
┌─────────────────────────────────────┐
│ ## 第一章:系统架构                   │
│                                     │
│ 本章介绍系统的整体架构设计。          │
│                                     │
│ ### 1.1 架构概述                     │
│                                     │
│ 系统采用微服务架构,包含以下核心模块: │
│ - 用户服务                          │
│ - 订单服务                          │
│ - 支付服务                          │
│                                     │
│ ### 1.2 技术选型                     │
│                                     │
│ 我们选择了以下技术栈...              │
└─────────────────────────────────────┘

当前切块方式(固定512 tokens):
┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
│ Chunk 1:        │  │ Chunk 2:        │  │ Chunk 3:        │
│ ## 第一章:系统  │  │ 服务            │  │ 技术选型        │
│ 架构            │  │ - 订单服务       │  │ 我们选择了以下   │
│                 │  │ - 支付服务       │  │ 技术栈...       │
│ 本章介绍系统的   │  │                 │  │                 │
│ 整体架构设计。   │  │ ### 1.2         │  │                 │
│                 │  │                 │  │                 │
│ ### 1.1 架构概述 │  │                 │  │                 │
│                 │  │                 │  │                 │
│ 系统采用微服务   │  │                 │  │                 │
│ 架构,包含以下   │  │                 │  │                 │
│ 核心模块:       │  │                 │  │                 │
│ - 用户服务       │  │                 │  │                 │
└─────────────────┘  └─────────────────┘  └─────────────────┘

问题:
❌ 章节标题被切断
❌ 列表项被分散
❌ 失去上下文关系
❌ 检索时难以理解完整语义

问题2: 无法利用文档结构信息 ​

用户问题: "系统架构包含哪些核心模块?"

当前检索:
1. 检索到 Chunk 1(包含"核心模块"关键词)
2. 但只能看到部分列表项
3. 无法获取完整的模块列表

理想检索:
1. 识别问题属于"1.1 架构概述"章节
2. 返回完整的章节内容
3. 包含所有列表项和相关说明

问题3: 检索质量不稳定 ​

场景1: 精确匹配
Q: "支付服务的功能是什么?"
当前: 可能检索到包含"支付服务"的多个chunk,但缺少上下文

场景2: 概念查询
Q: "系统的整体设计思路是什么?"
当前: 难以定位到高层次的章节内容

场景3: 细节查询
Q: "订单服务使用了什么数据库?"
当前: 可能检索到不相关的技术栈描述

1.2 MinerU的优势 ​

MinerU是一个强大的文档解析工具,能够:

  1. 保留文档结构

    • 识别标题层级(H1-H6)
    • 识别段落、列表、表格
    • 识别代码块、引用块
    • 识别图片、公式
  2. 输出结构化Markdown

    markdown
    # 第一章:系统架构
    
    本章介绍系统的整体架构设计。
    
    ## 1.1 架构概述
    
    系统采用微服务架构,包含以下核心模块:
    - 用户服务
    - 订单服务
    - 支付服务
    
    ## 1.2 技术选型
    
    我们选择了以下技术栈...
  3. 提供元数据

    • 页码信息
    • 位置坐标
    • 字体样式
    • 图片引用

2. 现状分析 ​

2.1 当前向量化流程 ​

┌──────────────┐
│  上传文档     │
│  (PDF/Word)  │
└──────┬───────┘
       │
       ↓
┌──────────────┐
│  文本提取     │  ← 简单提取,丢失结构
│ (Apache Tika)│
└──────┬───────┘
       │
       ↓
┌──────────────┐
│  固定切块     │  ← 按512 tokens切分
│ (RecursiveCS)│
└──────┬───────┘
       │
       ↓
┌──────────────┐
│  批量向量化   │
│ (Embedding)  │
└──────┬───────┘
       │
       ↓
┌──────────────┐
│  存储到Milvus │
│  (Flat结构)  │
└──────────────┘

当前数据结构:

java
kb_chunk 表:
- id
- document_id
- content           // 纯文本内容
- chunk_index       // 顺序索引
- token_count       // token数量
- vector            // 向量(存在Milvus)

问题:
❌ 没有结构信息
❌ 没有层级关系
❌ 没有类型标识
❌ 没有上下文引用

2.2 当前检索流程 ​

用户查询: "系统架构的核心模块"
       ↓
向量化查询
       ↓
Milvus相似度检索 (Top-K)
       ↓
返回 K 个chunks
       ↓
拼接成上下文
       ↓
送入LLM生成答案

问题:

  • 检索到的chunks可能来自不同章节
  • 无法保证语义连贯性
  • 缺少层级上下文
  • 无法识别内容类型(代码、表格、正文)

3. 设计目标 ​

3.1 核心目标 ​

目标1: 保留文档结构 ​

✅ 完整保留文档的层级结构
✅ 识别章节、段落、列表、表格等元素
✅ 建立父子关系和兄弟关系
✅ 支持多种文档类型(PDF、Word、Markdown)

目标2: 智能分块策略 ​

✅ 基于语义完整性分块(而非固定大小)
✅ 保持章节的完整性
✅ 保持列表的完整性
✅ 保持表格的完整性
✅ 支持大章节的智能拆分

目标3: 多级向量化 ​

✅ 文档级向量(全文摘要)
✅ 章节级向量(一级标题)
✅ 小节级向量(二级标题)
✅ 段落级向量(具体内容)
✅ 元数据向量(图表、代码)

目标4: 增强检索能力 ​

✅ 支持结构化检索(按章节、类型)
✅ 支持层级检索(父子关系)
✅ 支持混合检索(结构+语义)
✅ 支持精确定位(页码、章节号)

3.2 非功能性目标 ​

性能目标 ​

✅ 解析速度: 1000页文档 < 5分钟
✅ 向量化速度: 与当前方案相当
✅ 检索延迟: < 500ms (P95)
✅ 存储效率: 不超过当前方案的150%

兼容性目标 ​

✅ 向后兼容现有chunk方式
✅ 支持渐进式迁移
✅ 支持配置化切换
✅ 保留现有API接口

可扩展性目标 ​

✅ 支持新的文档类型扩展
✅ 支持新的分块策略扩展
✅ 支持新的检索策略扩展
✅ 支持新的元数据类型扩展

4. 整体架构 ​

4.1 系统架构图 ​

┌─────────────────────────────────────────────────────────────────┐
│                         文档上传层                                │
├─────────────────────────────────────────────────────────────────┤
│  PDF文档  │  Word文档  │  Markdown  │  HTML  │  其他格式         │
└────┬──────┴────┬───────┴────┬───────┴────┬────┴─────┬───────────┘
     │           │            │            │          │
     └───────────┴────────────┴────────────┴──────────┘
                              │
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│                      文档解析层                                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌─────────────┐     ┌─────────────┐     ┌─────────────┐      │
│  │  MinerU     │     │  Apache     │     │  Custom     │      │
│  │  Parser     │     │  Tika       │     │  Parser     │      │
│  └──────┬──────┘     └──────┬──────┘     └──────┬──────┘      │
│         │                    │                    │             │
│         └────────────────────┴────────────────────┘             │
│                              │                                  │
│                              ↓                                  │
│                    ┌──────────────────┐                         │
│                    │  统一文档模型     │                         │
│                    │  (Document Tree) │                         │
│                    └────────┬─────────┘                         │
└─────────────────────────────┼─────────────────────────────────┘
                              │
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│                      结构分析层                                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────┐ │
│  │  结构识别器       │  │  语义分析器       │  │  元数据提取器 │ │
│  │ - 章节识别        │  │ - 主题识别        │  │ - 页码提取   │ │
│  │ - 层级构建        │  │ - 关键词提取      │  │ - 图表识别   │ │
│  │ - 类型标注        │  │ - 摘要生成        │  │ - 代码识别   │ │
│  └────────┬─────────┘  └────────┬─────────┘  └────────┬───────┘ │
│           │                     │                     │         │
│           └─────────────────────┴─────────────────────┘         │
│                              │                                  │
│                              ↓                                  │
│                    ┌──────────────────┐                         │
│                    │  结构化文档树     │                         │
│                    │  (Enriched Tree) │                         │
│                    └────────┬─────────┘                         │
└─────────────────────────────┼─────────────────────────────────┘
                              │
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│                      分块策略层                                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │ 章节级分块    │  │ 段落级分块    │  │ 混合分块      │         │
│  │ - 按一级标题  │  │ - 按段落      │  │ - 智能组合    │         │
│  │ - 保持完整性  │  │ - 保持连贯    │  │ - 大小限制    │         │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘         │
│         │                  │                  │                 │
│         └──────────────────┴──────────────────┘                 │
│                            │                                    │
│                            ↓                                    │
│                 ┌────────────────────┐                          │
│                 │  智能Chunk生成器    │                          │
│                 │ - 语义完整性检查    │                          │
│                 │ - 大小平衡         │                          │
│                 │ - 重叠窗口生成     │                          │
│                 └──────────┬─────────┘                          │
└────────────────────────────┼────────────────────────────────────┘
                             │
                             ↓
┌─────────────────────────────────────────────────────────────────┐
│                      向量化层                                     │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │              多级向量化引擎                                │  │
│  │                                                            │  │
│  │  文档级向量 ─────┐                                         │  │
│  │  章节级向量 ─────┼─→  批量Embedding  ─→  向量池            │  │
│  │  段落级向量 ─────┤                                         │  │
│  │  元数据向量 ─────┘                                         │  │
│  │                                                            │  │
│  └──────────────────────────┬─────────────────────────────────┘  │
│                             │                                   │
│                             ↓                                   │
│              ┌───────────────────────────┐                      │
│              │     向量增强处理           │                      │
│              │ - 层级关系编码            │                      │
│              │ - 位置信息编码            │                      │
│              │ - 类型标签编码            │                      │
│              └───────────────┬───────────┘                      │
└──────────────────────────────┼──────────────────────────────────┘
                               │
                               ↓
┌─────────────────────────────────────────────────────────────────┐
│                      存储层                                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────────┐         ┌──────────────────┐             │
│  │   MySQL/PG       │         │     Milvus       │             │
│  │ ───────────────  │         │ ──────────────── │             │
│  │ kb_doc_node      │         │ node_vectors     │             │
│  │ - 结构信息        │         │ - 节点向量        │             │
│  │ - 层级关系        │◄────────┤ - 元数据         │             │
│  │ - 元数据          │         │ - 索引           │             │
│  │ kb_chunk         │         │                  │             │
│  │ - chunk内容       │         │                  │             │
│  │ - 节点引用        │         │                  │             │
│  └──────────────────┘         └──────────────────┘             │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
                               │
                               ↓
┌─────────────────────────────────────────────────────────────────┐
│                      检索层                                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │ 结构化检索   │  │ 语义检索     │  │ 混合检索     │            │
│  │ - 按章节     │  │ - 向量相似度 │  │ - 加权融合   │            │
│  │ - 按类型     │  │ - 语义匹配   │  │ - 重排序     │            │
│  │ - 按层级     │  │ - Top-K      │  │ - 上下文扩展 │            │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘            │
│         │                 │                 │                  │
│         └─────────────────┴─────────────────┘                  │
│                           │                                    │
│                           ↓                                    │
│                ┌────────────────────┐                          │
│                │  检索结果后处理     │                          │
│                │ - 去重               │                          │
│                │ - 上下文补全         │                          │
│                │ - 层级展开           │                          │
│                │ - 引用标注           │                          │
│                └──────────┬─────────┘                          │
└───────────────────────────┼────────────────────────────────────┘
                            │
                            ↓
                    ┌───────────────┐
                    │  返回给用户    │
                    └───────────────┘

4.2 数据流图 ​

场景1: 文档上传到向量化 ​

[用户上传PDF文档]
        │
        ↓
[MinIO存储原始文件]
        │
        ↓
[MinerU解析]
        ├─→ 提取文本
        ├─→ 识别结构
        ├─→ 提取图表
        └─→ 生成Markdown
        │
        ↓
[构建文档树]
        ├─→ Document Node
        ├─→ Chapter Node
        ├─→ Section Node
        ├─→ Paragraph Node
        └─→ Table/Code/Image Node
        │
        ↓
[结构分析]
        ├─→ 层级关系
        ├─→ 语义标注
        └─→ 元数据提取
        │
        ↓
[智能分块]
        ├─→ 章节完整性检查
        ├─→ 大小平衡
        └─→ 生成Chunks
        │
        ↓
[多级向量化]
        ├─→ 文档级向量
        ├─→ 章节级向量
        └─→ Chunk级向量
        │
        ↓
[存储]
        ├─→ MySQL: 结构信息、元数据
        └─→ Milvus: 向量数据
        │
        ↓
[完成]

场景2: 用户查询到答案生成 ​

[用户输入查询: "系统的核心模块有哪些?"]
        │
        ↓
[查询分析]
        ├─→ 意图识别(查询核心模块)
        ├─→ 实体识别(系统、模块)
        └─→ 查询类型(列表查询)
        │
        ↓
[查询向量化]
        │
        ↓
[多路检索]
        ├─→ 路径1: 章节级检索
        │   └─→ 搜索"架构"、"核心模块"相关章节
        │
        ├─→ 路径2: 段落级检索
        │   └─→ 搜索具体描述模块的段落
        │
        └─→ 路径3: 结构化检索
            └─→ 搜索列表类型的内容
        │
        ↓
[结果融合]
        ├─→ 去重
        ├─→ 加权排序
        └─→ 选择Top-K
        │
        ↓
[上下文增强]
        ├─→ 获取父章节标题
        ├─→ 获取相邻段落
        └─→ 补全列表项
        │
        ↓
[构建Prompt]
        ├─→ 添加文档结构信息
        ├─→ 添加章节上下文
        └─→ 添加具体内容
        │
        ↓
[LLM生成答案]
        │
        ↓
[返回结果(附带引用)]
        ├─→ 答案文本
        ├─→ 来源章节
        ├─→ 页码信息
        └─→ 置信度

5. 核心模块设计 ​

5.1 文档解析模块 (Document Parser Module) ​

5.1.1 模块职责 ​

┌─────────────────────────────────────┐
│      DocumentParserModule           │
├─────────────────────────────────────┤
│                                     │
│  职责:                               │
│  1. 解析多种格式的文档               │
│  2. 提取文本和结构信息               │
│  3. 识别文档元素类型                 │
│  4. 构建统一的文档模型               │
│                                     │
│  输入:                               │
│  - 原始文档文件(PDF/Word/MD等)       │
│  - 解析配置                          │
│                                     │
│  输出:                               │
│  - 结构化文档树(DocumentTree)        │
│  - 元数据(Metadata)                 │
│                                     │
└─────────────────────────────────────┘

5.1.2 解析器接口设计 ​

java
/**
 * 文档解析器接口
 */
public interface DocumentParser {

    /**
     * 支持的文档类型
     */
    Set<DocumentType> getSupportedTypes();

    /**
     * 解析文档
     * @param document 原始文档
     * @param config 解析配置
     * @return 文档树
     */
    DocumentTree parse(RawDocument document, ParserConfig config)
        throws ParseException;

    /**
     * 检查是否可以解析该文档
     */
    boolean canParse(RawDocument document);
}

/**
 * MinerU解析器实现
 */
public class MinerUParser implements DocumentParser {

    @Override
    public DocumentTree parse(RawDocument document, ParserConfig config) {
        // 1. 调用MinerU解析PDF
        MinerUResult minerUResult = minerUClient.parse(document.getPath());

        // 2. 解析Markdown输出
        String markdownContent = minerUResult.getMarkdown();

        // 3. 构建文档树
        DocumentTree tree = buildDocumentTree(markdownContent);

        // 4. 提取元数据
        tree.setMetadata(extractMetadata(minerUResult));

        // 5. 关联图片和表格
        attachAssets(tree, minerUResult.getImages(), minerUResult.getTables());

        return tree;
    }

    /**
     * 从Markdown构建文档树
     */
    private DocumentTree buildDocumentTree(String markdown) {
        // 使用Markdown解析器(如flexmark-java)
        // 识别标题层级、段落、列表、表格等
        // 构建树形结构
    }
}

5.1.3 解析配置 ​

java
/**
 * 解析配置
 */
public class ParserConfig {

    // 基础配置
    private boolean extractImages = true;        // 提取图片
    private boolean extractTables = true;        // 提取表格
    private boolean extractCodeBlocks = true;    // 提取代码块

    // 结构识别配置
    private int maxHeadingLevel = 6;             // 最大标题层级
    private boolean preserveFormatting = true;   // 保留格式信息

    // 质量控制
    private double minConfidence = 0.8;          // 最小置信度
    private boolean strictMode = false;          // 严格模式

    // MinerU特定配置
    private MinerUConfig minerUConfig;
}

5.1.4 文档树结构 ​

java
/**
 * 文档树
 */
public class DocumentTree {
    private DocumentNode root;                    // 根节点(文档)
    private Map<String, DocumentNode> nodeMap;   // ID -> 节点映射
    private DocumentMetadata metadata;            // 文档元数据

    /**
     * 遍历所有节点
     */
    public void traverse(Consumer<DocumentNode> visitor) {
        traverseNode(root, visitor);
    }

    /**
     * 查找节点
     */
    public DocumentNode findNode(String nodeId) {
        return nodeMap.get(nodeId);
    }

    /**
     * 获取所有叶子节点
     */
    public List<DocumentNode> getLeafNodes() {
        // 返回所有没有子节点的节点
    }
}

/**
 * 文档节点
 */
public class DocumentNode {
    // 基础信息
    private String id;                           // 唯一ID
    private NodeType type;                       // 节点类型
    private String content;                      // 文本内容

    // 结构信息
    private DocumentNode parent;                 // 父节点
    private List<DocumentNode> children;         // 子节点
    private int level;                           // 层级(从0开始)
    private int order;                           // 同级排序

    // 元数据
    private NodeMetadata metadata;               // 节点元数据

    // 位置信息
    private PageLocation location;               // 在原文档中的位置

    // 方法
    public boolean isLeaf();                     // 是否叶子节点
    public String getPath();                     // 获取路径(如 1.2.3)
    public String getTitle();                    // 获取标题
    public List<DocumentNode> getSiblings();     // 获取兄弟节点
    public DocumentNode getNextSibling();        // 获取下一个兄弟节点
    public DocumentNode getPrevSibling();        // 获取上一个兄弟节点
}

/**
 * 节点类型
 */
public enum NodeType {
    DOCUMENT,        // 文档根节点
    CHAPTER,         // 章(H1)
    SECTION,         // 节(H2)
    SUBSECTION,      // 小节(H3)
    PARAGRAPH,       // 段落
    LIST,            // 列表
    LIST_ITEM,       // 列表项
    TABLE,           // 表格
    CODE_BLOCK,      // 代码块
    QUOTE,           // 引用
    IMAGE,           // 图片
    FORMULA,         // 公式
    FOOTNOTE         // 脚注
}

/**
 * 节点元数据
 */
public class NodeMetadata {
    private String title;                        // 标题
    private Map<String, String> attributes;      // 属性
    private List<String> tags;                   // 标签
    private Double confidence;                   // 置信度

    // 特定类型的元数据
    private TableMetadata tableMetadata;         // 表格元数据
    private CodeMetadata codeMetadata;           // 代码元数据
    private ImageMetadata imageMetadata;         // 图片元数据
}

/**
 * 页面位置
 */
public class PageLocation {
    private int pageNumber;                      // 页码
    private Rectangle boundingBox;               // 边界框
    private int charOffset;                      // 字符偏移
}

5.2 结构分析模块 (Structure Analysis Module) ​

5.2.1 模块职责 ​

┌─────────────────────────────────────┐
│    StructureAnalysisModule          │
├─────────────────────────────────────┤
│                                     │
│  职责:                               │
│  1. 分析文档的逻辑结构               │
│  2. 识别章节主题和语义               │
│  3. 提取关键信息和摘要               │
│  4. 标注节点的语义类型               │
│                                     │
│  输入:                               │
│  - 初始文档树                        │
│                                     │
│  输出:                               │
│  - 增强的文档树                      │
│  - 语义标注                          │
│  - 摘要信息                          │
│                                     │
└─────────────────────────────────────┘

5.2.2 结构识别器 ​

java
/**
 * 结构识别器
 */
public class StructureRecognizer {

    /**
     * 识别文档结构
     */
    public void recognize(DocumentTree tree) {
        // 1. 识别章节层级
        recognizeHierarchy(tree);

        // 2. 识别特殊结构
        recognizeSpecialStructures(tree);

        // 3. 建立引用关系
        buildReferences(tree);
    }

    /**
     * 识别章节层级
     */
    private void recognizeHierarchy(DocumentTree tree) {
        tree.traverse(node -> {
            if (node.getType() == NodeType.CHAPTER) {
                // 识别章节编号 (如 "1.2.3")
                String chapterNumber = extractChapterNumber(node.getTitle());
                node.getMetadata().setAttribute("chapterNumber", chapterNumber);

                // 计算层级深度
                int depth = calculateDepth(chapterNumber);
                node.getMetadata().setAttribute("depth", String.valueOf(depth));
            }
        });
    }

    /**
     * 识别特殊结构
     */
    private void recognizeSpecialStructures(DocumentTree tree) {
        // 识别目录
        recognizeTableOfContents(tree);

        // 识别参考文献
        recognizeReferences(tree);

        // 识别附录
        recognizeAppendix(tree);

        // 识别图表列表
        recognizeFigureList(tree);
    }
}

5.2.3 语义分析器 ​

java
/**
 * 语义分析器
 */
public class SemanticAnalyzer {

    private final LLMClient llmClient;  // 可选:使用LLM进行语义分析

    /**
     * 分析文档语义
     */
    public void analyze(DocumentTree tree) {
        // 1. 提取章节摘要
        extractSummaries(tree);

        // 2. 识别主题
        identifyTopics(tree);

        // 3. 提取关键词
        extractKeywords(tree);

        // 4. 识别内容类型
        classifyContent(tree);
    }

    /**
     * 提取章节摘要
     */
    private void extractSummaries(DocumentTree tree) {
        tree.traverse(node -> {
            if (node.getType() == NodeType.CHAPTER ||
                node.getType() == NodeType.SECTION) {

                // 收集该章节下的所有段落
                String fullContent = collectContent(node);

                // 生成摘要(可以使用LLM或传统方法)
                String summary = generateSummary(fullContent);

                node.getMetadata().setAttribute("summary", summary);
            }
        });
    }

    /**
     * 识别内容类型
     */
    private void classifyContent(DocumentTree tree) {
        tree.traverse(node -> {
            if (node.getType() == NodeType.PARAGRAPH) {
                ContentType contentType = classifyParagraph(node.getContent());
                node.getMetadata().setAttribute("contentType", contentType.name());
            }
        });
    }

    /**
     * 分类段落类型
     */
    private ContentType classifyParagraph(String content) {
        // 规则分类或ML分类
        if (containsCodePattern(content)) {
            return ContentType.CODE_DESCRIPTION;
        } else if (containsSteps(content)) {
            return ContentType.TUTORIAL;
        } else if (containsDefinition(content)) {
            return ContentType.DEFINITION;
        } else if (containsExample(content)) {
            return ContentType.EXAMPLE;
        } else {
            return ContentType.GENERAL;
        }
    }
}

/**
 * 内容类型
 */
public enum ContentType {
    GENERAL,              // 一般说明
    DEFINITION,           // 定义
    EXPLANATION,          // 解释
    TUTORIAL,             // 教程步骤
    EXAMPLE,              // 示例
    CODE_DESCRIPTION,     // 代码说明
    REFERENCE,            // 参考信息
    SUMMARY,              // 总结
    COMPARISON            // 对比
}

5.3 智能分块模块 (Intelligent Chunking Module) ​

5.3.1 模块职责 ​

┌─────────────────────────────────────┐
│   IntelligentChunkingModule         │
├─────────────────────────────────────┤
│                                     │
│  职责:                               │
│  1. 基于文档结构进行智能分块         │
│  2. 保持语义完整性                   │
│  3. 控制chunk大小                    │
│  4. 生成重叠窗口                     │
│                                     │
│  输入:                               │
│  - 增强的文档树                      │
│  - 分块策略配置                      │
│                                     │
│  输出:                               │
│  - Chunk列表                         │
│  - Chunk与节点的映射关系             │
│                                     │
└─────────────────────────────────────┘

5.3.2 分块策略 ​

java
/**
 * 分块策略接口
 */
public interface ChunkingStrategy {

    /**
     * 对文档树进行分块
     */
    List<Chunk> chunk(DocumentTree tree, ChunkingConfig config);

    /**
     * 策略名称
     */
    String getName();
}

/**
 * 章节级分块策略
 */
public class SectionBasedChunkingStrategy implements ChunkingStrategy {

    @Override
    public List<Chunk> chunk(DocumentTree tree, ChunkingConfig config) {
        List<Chunk> chunks = new ArrayList<>();

        tree.traverse(node -> {
            // 只对章节级节点进行分块
            if (node.getType() == NodeType.CHAPTER ||
                node.getType() == NodeType.SECTION) {

                // 收集该章节下的所有内容
                String content = collectSectionContent(node);

                // 检查大小
                int tokenCount = countTokens(content);

                if (tokenCount <= config.getMaxChunkSize()) {
                    // 整个章节作为一个chunk
                    chunks.add(createChunk(node, content));
                } else {
                    // 章节太大,需要拆分
                    chunks.addAll(splitLargeSection(node, content, config));
                }
            }
        });

        return chunks;
    }

    /**
     * 拆分大章节
     */
    private List<Chunk> splitLargeSection(DocumentNode node, String content,
                                          ChunkingConfig config) {
        List<Chunk> chunks = new ArrayList<>();

        // 策略1: 按子章节拆分
        if (node.hasChildren()) {
            for (DocumentNode child : node.getChildren()) {
                String childContent = collectSectionContent(child);
                chunks.add(createChunk(child, childContent));
            }
        }
        // 策略2: 按段落拆分
        else {
            List<DocumentNode> paragraphs = findParagraphs(node);
            chunks.addAll(groupParagraphsIntoChunks(paragraphs, config));
        }

        return chunks;
    }
}

/**
 * 段落级分块策略
 */
public class ParagraphBasedChunkingStrategy implements ChunkingStrategy {

    @Override
    public List<Chunk> chunk(DocumentTree tree, ChunkingConfig config) {
        List<Chunk> chunks = new ArrayList<>();
        List<DocumentNode> paragraphs = new ArrayList<>();

        // 收集所有段落
        tree.traverse(node -> {
            if (node.getType() == NodeType.PARAGRAPH) {
                paragraphs.add(node);
            }
        });

        // 将段落分组成chunks
        return groupParagraphsIntoChunks(paragraphs, config);
    }

    /**
     * 将段落分组成chunks
     */
    private List<Chunk> groupParagraphsIntoChunks(List<DocumentNode> paragraphs,
                                                   ChunkingConfig config) {
        List<Chunk> chunks = new ArrayList<>();
        StringBuilder currentContent = new StringBuilder();
        List<DocumentNode> currentNodes = new ArrayList<>();
        int currentTokens = 0;

        for (DocumentNode paragraph : paragraphs) {
            String paragraphContent = paragraph.getContent();
            int paragraphTokens = countTokens(paragraphContent);

            // 检查是否会超过限制
            if (currentTokens + paragraphTokens > config.getMaxChunkSize() &&
                currentTokens > 0) {
                // 创建当前chunk
                chunks.add(createChunk(currentNodes, currentContent.toString()));

                // 重置
                currentContent = new StringBuilder();
                currentNodes = new ArrayList<>();
                currentTokens = 0;
            }

            // 添加段落
            currentContent.append(paragraphContent).append("\n\n");
            currentNodes.add(paragraph);
            currentTokens += paragraphTokens;
        }

        // 添加最后一个chunk
        if (currentTokens > 0) {
            chunks.add(createChunk(currentNodes, currentContent.toString()));
        }

        return chunks;
    }
}

/**
 * 混合分块策略(推荐)
 */
public class HybridChunkingStrategy implements ChunkingStrategy {

    @Override
    public List<Chunk> chunk(DocumentTree tree, ChunkingConfig config) {
        List<Chunk> chunks = new ArrayList<>();

        tree.traverse(node -> {
            // 对不同类型的节点使用不同策略
            switch (node.getType()) {
                case CHAPTER:
                case SECTION:
                    chunks.addAll(chunkSection(node, config));
                    break;
                case TABLE:
                    chunks.add(chunkTable(node));
                    break;
                case CODE_BLOCK:
                    chunks.add(chunkCodeBlock(node));
                    break;
                case LIST:
                    chunks.add(chunkList(node));
                    break;
            }
        });

        return chunks;
    }

    /**
     * 对章节进行分块
     */
    private List<Chunk> chunkSection(DocumentNode node, ChunkingConfig config) {
        // 1. 获取章节标题和摘要
        String title = node.getTitle();
        String summary = node.getMetadata().getAttribute("summary");

        // 2. 收集内容
        String content = collectSectionContent(node);
        int totalTokens = countTokens(content);

        // 3. 判断是否需要拆分
        if (totalTokens <= config.getMaxChunkSize()) {
            // 不需要拆分,保持章节完整性
            Chunk chunk = Chunk.builder()
                .content(content)
                .title(title)
                .summary(summary)
                .sourceNode(node)
                .type(ChunkType.SECTION)
                .build();
            return Collections.singletonList(chunk);
        } else {
            // 需要拆分,按子节点或段落拆分
            return splitSection(node, config);
        }
    }
}

5.3.3 Chunk数据结构 ​

java
/**
 * Chunk
 */
@Data
@Builder
public class Chunk {
    // 基础信息
    private String id;                           // Chunk ID
    private String content;                      // 文本内容
    private int tokenCount;                      // Token数量

    // 结构信息
    private ChunkType type;                      // Chunk类型
    private String title;                        // 标题
    private String summary;                      // 摘要

    // 关联信息
    private List<String> sourceNodeIds;          // 来源节点ID列表
    private String parentChunkId;                // 父Chunk ID
    private List<String> childChunkIds;          // 子Chunk ID列表

    // 上下文信息
    private String contextBefore;                // 前文上下文
    private String contextAfter;                 // 后文上下文
    private String chapterPath;                  // 章节路径 (如 "1.2.3")

    // 位置信息
    private int pageNumber;                      // 页码
    private int chunkIndex;                      // 在文档中的顺序

    // 元数据
    private Map<String, String> metadata;        // 额外元数据

    // 向量信息(稍后添加)
    private float[] vector;                      // 向量(可选,也可以只存在Milvus)
}

/**
 * Chunk类型
 */
public enum ChunkType {
    SECTION,         // 章节
    PARAGRAPH,       // 段落
    TABLE,           // 表格
    CODE,            // 代码
    LIST,            // 列表
    MIXED            // 混合
}

5.3.4 重叠窗口生成 ​

java
/**
 * 重叠窗口生成器
 */
public class OverlapWindowGenerator {

    /**
     * 为chunks添加重叠窗口
     */
    public void addOverlapWindows(List<Chunk> chunks, ChunkingConfig config) {
        int overlapSize = config.getOverlapSize();

        for (int i = 0; i < chunks.size(); i++) {
            Chunk currentChunk = chunks.get(i);

            // 添加前文上下文
            if (i > 0) {
                Chunk prevChunk = chunks.get(i - 1);
                String contextBefore = extractContext(prevChunk, overlapSize, false);
                currentChunk.setContextBefore(contextBefore);
            }

            // 添加后文上下文
            if (i < chunks.size() - 1) {
                Chunk nextChunk = chunks.get(i + 1);
                String contextAfter = extractContext(nextChunk, overlapSize, true);
                currentChunk.setContextAfter(contextAfter);
            }
        }
    }

    /**
     * 提取上下文
     */
    private String extractContext(Chunk chunk, int size, boolean fromStart) {
        String content = chunk.getContent();

        if (fromStart) {
            // 从开头提取
            return content.substring(0, Math.min(size, content.length()));
        } else {
            // 从结尾提取
            int start = Math.max(0, content.length() - size);
            return content.substring(start);
        }
    }
}

5.4 向量化策略模块 (Vectorization Strategy Module) ​

5.4.1 多级向量化 ​

java
/**
 * 多级向量化引擎
 */
public class MultiLevelVectorizationEngine {

    private final EmbeddingModelFactory embeddingModelFactory;

    /**
     * 执行多级向量化
     */
    public VectorizationResult vectorize(DocumentTree tree,
                                         List<Chunk> chunks,
                                         VectorizationConfig config) {
        VectorizationResult result = new VectorizationResult();

        // Level 1: 文档级向量
        if (config.isEnableDocumentLevelVector()) {
            result.setDocumentVector(vectorizeDocument(tree));
        }

        // Level 2: 章节级向量
        if (config.isEnableChapterLevelVector()) {
            result.setChapterVectors(vectorizeChapters(tree));
        }

        // Level 3: Chunk级向量
        result.setChunkVectors(vectorizeChunks(chunks));

        return result;
    }

    /**
     * 文档级向量化
     */
    private DocumentVector vectorizeDocument(DocumentTree tree) {
        // 生成文档摘要
        String documentSummary = generateDocumentSummary(tree);

        // 向量化摘要
        float[] vector = embeddingModel.embed(documentSummary);

        return DocumentVector.builder()
            .documentId(tree.getMetadata().getDocumentId())
            .summary(documentSummary)
            .vector(vector)
            .build();
    }

    /**
     * 章节级向量化
     */
    private List<ChapterVector> vectorizeChapters(DocumentTree tree) {
        List<ChapterVector> chapterVectors = new ArrayList<>();

        tree.traverse(node -> {
            if (node.getType() == NodeType.CHAPTER ||
                node.getType() == NodeType.SECTION) {

                // 构建章节内容(标题 + 摘要 + 关键段落)
                String chapterContent = buildChapterContent(node);

                // 向量化
                float[] vector = embeddingModel.embed(chapterContent);

                chapterVectors.add(ChapterVector.builder()
                    .nodeId(node.getId())
                    .title(node.getTitle())
                    .level(node.getLevel())
                    .vector(vector)
                    .build());
            }
        });

        return chapterVectors;
    }

    /**
     * Chunk级向量化
     */
    private List<ChunkVector> vectorizeChunks(List<Chunk> chunks) {
        // 批量向量化
        List<String> contents = chunks.stream()
            .map(Chunk::getContent)
            .collect(Collectors.toList());

        List<float[]> vectors = embeddingModel.embedBatch(contents);

        // 构建ChunkVector
        List<ChunkVector> chunkVectors = new ArrayList<>();
        for (int i = 0; i < chunks.size(); i++) {
            chunkVectors.add(ChunkVector.builder()
                .chunkId(chunks.get(i).getId())
                .vector(vectors.get(i))
                .build());
        }

        return chunkVectors;
    }
}

6. 数据模型设计 ​

6.1 数据库表设计 ​

6.1.1 文档节点表 (kb_doc_node) ​

sql
CREATE TABLE `kb_doc_node` (
    `id` BIGINT NOT NULL COMMENT '节点ID',
    `document_id` BIGINT NOT NULL COMMENT '文档ID',
    `parent_id` BIGINT NULL COMMENT '父节点ID',

    -- 节点信息
    `node_type` VARCHAR(50) NOT NULL COMMENT '节点类型:DOCUMENT/CHAPTER/SECTION/PARAGRAPH等',
    `title` VARCHAR(500) NULL COMMENT '标题',
    `content` TEXT NULL COMMENT '内容',
    `content_hash` VARCHAR(64) NULL COMMENT '内容哈希',

    -- 结构信息
    `level` INT NOT NULL COMMENT '层级(0=文档根节点)',
    `order_index` INT NOT NULL COMMENT '同级排序',
    `path` VARCHAR(200) NULL COMMENT '路径(如 1.2.3)',

    -- 位置信息
    `page_number` INT NULL COMMENT '页码',
    `char_offset` INT NULL COMMENT '字符偏移',
    `bounding_box` JSON NULL COMMENT '边界框(MinerU提供)',

    -- 元数据
    `metadata` JSON NULL COMMENT '元数据(summary, keywords, contentType等)',
    `confidence` DOUBLE NULL COMMENT '置信度',

    -- 统计信息
    `token_count` INT NULL COMMENT 'Token数量',
    `char_count` INT NULL COMMENT '字符数量',

    -- 审计字段
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `del_flag` CHAR(1) DEFAULT '0',
    `tenant_id` BIGINT NULL,

    PRIMARY KEY (`id`),
    KEY `idx_document_id` (`document_id`),
    KEY `idx_parent_id` (`parent_id`),
    KEY `idx_node_type` (`node_type`),
    KEY `idx_path` (`path`)
) COMMENT='文档节点表(存储文档树结构)';

6.1.2 智能Chunk表 (kb_smart_chunk) ​

sql
CREATE TABLE `kb_smart_chunk` (
    `id` BIGINT NOT NULL COMMENT 'Chunk ID',
    `document_id` BIGINT NOT NULL COMMENT '文档ID',
    `dataset_id` BIGINT NOT NULL COMMENT '数据集ID',

    -- Chunk信息
    `chunk_type` VARCHAR(50) NOT NULL COMMENT 'Chunk类型:SECTION/PARAGRAPH/TABLE等',
    `content` TEXT NOT NULL COMMENT '内容',
    `content_hash` VARCHAR(64) NOT NULL COMMENT '内容哈希',

    -- 结构信息
    `title` VARCHAR(500) NULL COMMENT '标题',
    `summary` TEXT NULL COMMENT '摘要',
    `chapter_path` VARCHAR(200) NULL COMMENT '章节路径',

    -- 关联信息
    `source_node_ids` JSON NOT NULL COMMENT '来源节点ID列表',
    `parent_chunk_id` BIGINT NULL COMMENT '父Chunk ID',

    -- 上下文信息
    `context_before` TEXT NULL COMMENT '前文上下文',
    `context_after` TEXT NULL COMMENT '后文上下文',

    -- 位置信息
    `page_number` INT NULL COMMENT '页码',
    `chunk_index` INT NOT NULL COMMENT '在文档中的顺序',

    -- 统计信息
    `token_count` INT NOT NULL COMMENT 'Token数量',
    `char_count` INT NOT NULL COMMENT '字符数量',

    -- 元数据
    `metadata` JSON NULL COMMENT '元数据',

    -- 审计字段
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `del_flag` CHAR(1) DEFAULT '0',
    `tenant_id` BIGINT NULL,

    PRIMARY KEY (`id`),
    KEY `idx_document_id` (`document_id`),
    KEY `idx_dataset_id` (`dataset_id`),
    KEY `idx_chunk_type` (`chunk_type`),
    KEY `idx_parent_chunk_id` (`parent_chunk_id`),
    KEY `idx_chapter_path` (`chapter_path`)
) COMMENT='智能Chunk表';

6.1.3 向量索引映射表 (kb_vector_index) ​

sql
CREATE TABLE `kb_vector_index` (
    `id` BIGINT NOT NULL COMMENT 'ID',
    `vector_id` VARCHAR(100) NOT NULL COMMENT 'Milvus向量ID',

    -- 关联信息
    `entity_type` VARCHAR(50) NOT NULL COMMENT '实体类型:DOCUMENT/CHAPTER/CHUNK',
    `entity_id` BIGINT NOT NULL COMMENT '实体ID',

    -- 向量信息
    `vector_level` VARCHAR(20) NOT NULL COMMENT '向量级别:DOCUMENT/CHAPTER/CHUNK',
    `dimension` INT NOT NULL COMMENT '向量维度',

    -- 元数据(用于检索过滤)
    `document_id` BIGINT NOT NULL,
    `dataset_id` BIGINT NOT NULL,
    `node_type` VARCHAR(50) NULL,
    `chunk_type` VARCHAR(50) NULL,
    `page_number` INT NULL,

    -- 审计字段
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `tenant_id` BIGINT NULL,

    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_vector_id` (`vector_id`),
    KEY `idx_entity` (`entity_type`, `entity_id`),
    KEY `idx_document_id` (`document_id`),
    KEY `idx_dataset_id` (`dataset_id`)
) COMMENT='向量索引映射表';

6.2 Milvus Collection设计 ​

6.2.1 统一向量Collection(推荐) ​

python
# Collection Schema
collection_schema = {
    "name": "kb_vectors_unified",
    "description": "统一的知识库向量存储",
    "fields": [
        # 主键
        {
            "name": "id",
            "type": DataType.INT64,
            "is_primary": True,
            "auto_id": False
        },

        # 向量字段
        {
            "name": "vector",
            "type": DataType.FLOAT_VECTOR,
            "dim": 1536  # 根据实际模型调整
        },

        # 标量字段(用于过滤)
        {
            "name": "document_id",
            "type": DataType.INT64
        },
        {
            "name": "dataset_id",
            "type": DataType.INT64
        },
        {
            "name": "entity_type",
            "type": DataType.VARCHAR,
            "max_length": 50
        },
        {
            "name": "entity_id",
            "type": DataType.INT64
        },
        {
            "name": "vector_level",
            "type": DataType.VARCHAR,
            "max_length": 20
        },
        {
            "name": "node_type",
            "type": DataType.VARCHAR,
            "max_length": 50
        },
        {
            "name": "chunk_type",
            "type": DataType.VARCHAR,
            "max_length": 50
        },
        {
            "name": "page_number",
            "type": DataType.INT32
        }
    ]
}

# 索引配置
index_params = {
    "metric_type": "COSINE",  # 或 "L2", "IP"
    "index_type": "HNSW",     # 推荐HNSW,性能好
    "params": {
        "M": 16,              # HNSW参数
        "efConstruction": 200
    }
}

6.2.2 分层向量Collection(可选,性能更优) ​

python
# 文档级向量Collection
document_vectors = {
    "name": "kb_document_vectors",
    "fields": [
        {"name": "id", "type": DataType.INT64, "is_primary": True},
        {"name": "vector", "type": DataType.FLOAT_VECTOR, "dim": 1536},
        {"name": "document_id", "type": DataType.INT64},
        {"name": "dataset_id", "type": DataType.INT64}
    ]
}

# 章节级向量Collection
chapter_vectors = {
    "name": "kb_chapter_vectors",
    "fields": [
        {"name": "id", "type": DataType.INT64, "is_primary": True},
        {"name": "vector", "type": DataType.FLOAT_VECTOR, "dim": 1536},
        {"name": "node_id", "type": DataType.INT64},
        {"name": "document_id", "type": DataType.INT64},
        {"name": "level", "type": DataType.INT32},
        {"name": "node_type", "type": DataType.VARCHAR, "max_length": 50}
    ]
}

# Chunk级向量Collection
chunk_vectors = {
    "name": "kb_chunk_vectors",
    "fields": [
        {"name": "id", "type": DataType.INT64, "is_primary": True},
        {"name": "vector", "type": DataType.FLOAT_VECTOR, "dim": 1536},
        {"name": "chunk_id", "type": DataType.INT64},
        {"name": "document_id", "type": DataType.INT64},
        {"name": "chunk_type", "type": DataType.VARCHAR, "max_length": 50}
    ]
}

选择建议:

  • 数据量 < 100万: 使用统一Collection(简单)
  • 数据量 > 100万: 使用分层Collection(性能更好)

7. 向量化策略 ​

7.1 向量化配置扩展 ​

在现有的 VectorizationConfig 基础上增加结构化向量化配置:

java
/**
 * 结构化向量化配置
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class StructuredVectorizationConfig extends VectorizationConfig {

    // ==================== 分块策略 ====================

    /**
     * 分块策略类型
     */
    @Builder.Default
    private ChunkingStrategyType chunkingStrategy = ChunkingStrategyType.HYBRID;

    // ==================== 多级向量化配置 ====================

    /**
     * 启用文档级向量
     */
    @Builder.Default
    private Boolean enableDocumentLevelVector = true;

    /**
     * 启用章节级向量
     */
    @Builder.Default
    private Boolean enableChapterLevelVector = true;

    /**
     * 启用Chunk级向量
     */
    @Builder.Default
    private Boolean enableChunkLevelVector = true;

    // ==================== 上下文配置 ====================

    /**
     * 上下文窗口大小(tokens)
     */
    @Builder.Default
    private Integer contextWindowSize = 200;

    /**
     * 包含章节标题
     */
    @Builder.Default
    private Boolean includeChapterTitle = true;

    /**
     * 包含摘要
     */
    @Builder.Default
    private Boolean includeSummary = true;

    // ==================== 特殊元素处理 ====================

    /**
     * 表格向量化策略
     */
    @Builder.Default
    private TableVectorizationStrategy tableStrategy = TableVectorizationStrategy.STRUCTURED;

    /**
     * 代码向量化策略
     */
    @Builder.Default
    private CodeVectorizationStrategy codeStrategy = CodeVectorizationStrategy.WITH_DESCRIPTION;

    /**
     * 图片向量化策略
     */
    @Builder.Default
    private ImageVectorizationStrategy imageStrategy = ImageVectorizationStrategy.CAPTION;

    // ==================== 质量控制 ====================

    /**
     * 最小章节tokens
     */
    @Builder.Default
    private Integer minSectionTokens = 50;

    /**
     * 最大章节tokens
     */
    @Builder.Default
    private Integer maxSectionTokens = 2000;

    /**
     * 跳过空章节
     */
    @Builder.Default
    private Boolean skipEmptySections = true;
}

/**
 * 分块策略类型
 */
public enum ChunkingStrategyType {
    SECTION_BASED,      // 基于章节
    PARAGRAPH_BASED,    // 基于段落
    HYBRID,             // 混合(推荐)
    LEGACY_FIXED        // 传统固定大小(向后兼容)
}

/**
 * 表格向量化策略
 */
public enum TableVectorizationStrategy {
    SKIP,               // 跳过表格
    AS_TEXT,            // 作为纯文本
    STRUCTURED,         // 结构化(保留表头和格式)
    WITH_DESCRIPTION    // 带描述文本
}

/**
 * 代码向量化策略
 */
public enum CodeVectorizationStrategy {
    SKIP,               // 跳过代码
    AS_TEXT,            // 作为纯文本
    WITH_DESCRIPTION,   // 带描述(推荐)
    WITH_COMMENTS       // 包含注释
}

/**
 * 图片向量化策略
 */
public enum ImageVectorizationStrategy {
    SKIP,               // 跳过图片
    CAPTION,            // 使用图片说明(推荐)
    OCR,                // OCR识别文字
    MULTIMODAL          // 多模态向量(未来扩展)
}

7.2 向量化流程 ​

java
/**
 * 结构化向量化服务
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class StructuredVectorizationService {

    private final DocumentParser documentParser;
    private final StructureAnalyzer structureAnalyzer;
    private final ChunkingStrategyFactory chunkingStrategyFactory;
    private final MultiLevelVectorizationEngine vectorizationEngine;
    private final DocNodeService docNodeService;
    private final SmartChunkService smartChunkService;

    /**
     * 执行结构化向量化
     */
    @Transactional(rollbackFor = Exception.class)
    public StructuredVectorizationResult vectorize(
            Long documentId,
            StructuredVectorizationConfig config) {

        log.info("开始结构化向量化: documentId={}", documentId);
        long startTime = System.currentTimeMillis();

        try {
            // Phase 1: 文档解析
            DocumentTree tree = parseDocument(documentId);
            log.info("文档解析完成: 节点数={}", tree.getNodeCount());

            // Phase 2: 结构分析
            analyzeStructure(tree);
            log.info("结构分析完成: 章节数={}", tree.getChapterCount());

            // Phase 3: 智能分块
            List<Chunk> chunks = chunkDocument(tree, config);
            log.info("智能分块完成: chunk数={}", chunks.size());

            // Phase 4: 多级向量化
            VectorizationResult vectorResult = vectorizeMultiLevel(tree, chunks, config);
            log.info("向量化完成: 向量数={}", vectorResult.getTotalVectorCount());

            // Phase 5: 存储
            saveToDatabase(tree, chunks, vectorResult);
            log.info("存储完成");

            // 构建结果
            long duration = System.currentTimeMillis() - startTime;
            return StructuredVectorizationResult.builder()
                .documentId(documentId)
                .nodeCount(tree.getNodeCount())
                .chunkCount(chunks.size())
                .vectorCount(vectorResult.getTotalVectorCount())
                .durationMs(duration)
                .success(true)
                .build();

        } catch (Exception e) {
            log.error("结构化向量化失败: documentId={}", documentId, e);
            throw new VectorizationException("结构化向量化失败", e);
        }
    }

    /**
     * 解析文档
     */
    private DocumentTree parseDocument(Long documentId) {
        // 获取文档信息
        KbDocumentEntity document = kbDocumentService.getById(documentId);

        // 选择合适的解析器
        DocumentParser parser = documentParserFactory.getParser(document.getFileType());

        // 解析文档
        RawDocument rawDocument = minioDocumentLoader.load(document);
        return parser.parse(rawDocument, ParserConfig.getDefault());
    }

    /**
     * 结构分析
     */
    private void analyzeStructure(DocumentTree tree) {
        // 识别结构
        structureAnalyzer.recognize(tree);

        // 语义分析
        structureAnalyzer.analyze(tree);
    }

    /**
     * 智能分块
     */
    private List<Chunk> chunkDocument(DocumentTree tree, StructuredVectorizationConfig config) {
        // 获取分块策略
        ChunkingStrategy strategy = chunkingStrategyFactory.getStrategy(
            config.getChunkingStrategy()
        );

        // 执行分块
        List<Chunk> chunks = strategy.chunk(tree, config);

        // 添加重叠窗口
        if (config.getContextWindowSize() > 0) {
            overlapWindowGenerator.addOverlapWindows(chunks, config);
        }

        return chunks;
    }

    /**
     * 多级向量化
     */
    private VectorizationResult vectorizeMultiLevel(
            DocumentTree tree,
            List<Chunk> chunks,
            StructuredVectorizationConfig config) {

        return vectorizationEngine.vectorize(tree, chunks, config);
    }

    /**
     * 保存到数据库
     */
    private void saveToDatabase(
            DocumentTree tree,
            List<Chunk> chunks,
            VectorizationResult vectorResult) {

        // 保存文档节点
        docNodeService.saveTree(tree);

        // 保存chunks
        smartChunkService.saveChunks(chunks);

        // 保存向量到Milvus
        milvusService.saveVectors(vectorResult);

        // 保存向量索引映射
        vectorIndexService.saveIndexMapping(vectorResult);
    }
}

8. 检索策略 ​

8.1 多路检索架构 ​

用户查询: "系统的核心模块有哪些?"
    │
    ↓
┌─────────────────────┐
│    查询分析器        │
│  - 意图识别          │
│  - 实体识别          │
│  - 查询类型分类      │
└──────────┬──────────┘
           │
           ↓
┌─────────────────────┐
│    检索路由器        │
│  根据查询类型选择路径│
└──────────┬──────────┘
           │
           ├─→ 路径1: 文档级检索
           │   └─ 适合: 文档摘要类查询
           │
           ├─→ 路径2: 章节级检索  ⭐
           │   └─ 适合: 查找特定主题章节
           │
           ├─→ 路径3: Chunk级检索
           │   └─ 适合: 细节查询
           │
           └─→ 路径4: 结构化检索
               └─ 适合: 列表、表格、代码查询
           │
           ↓
┌─────────────────────┐
│    并行检索执行      │
│  同时执行多个路径    │
└──────────┬──────────┘
           │
           ↓
┌─────────────────────┐
│    结果融合          │
│  - 去重              │
│  - 加权排序          │
│  - 选择Top-K         │
└──────────┬──────────┘
           │
           ↓
┌─────────────────────┐
│    上下文补全        │
│  - 获取父章节        │
│  - 获取相邻内容      │
│  - 补全列表项        │
└──────────┬──────────┘
           │
           ↓
┌─────────────────────┐
│    构建Prompt        │
│  - 添加结构信息      │
│  - 添加引用信息      │
└──────────┬──────────┘
           │
           ↓
        LLM生成答案

8.2 检索策略实现 ​

java
/**
 * 结构化检索服务
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class StructuredRetrievalService {

    private final QueryAnalyzer queryAnalyzer;
    private final RetrievalRouter retrievalRouter;
    private final MilvusClient milvusClient;
    private final DocNodeService docNodeService;
    private final SmartChunkService smartChunkService;
    private final Reranker reranker;
    private final ContextEnricher contextEnricher;

    /**
     * 执行结构化检索
     */
    public RetrievalResult retrieve(Query query, RetrievalConfig config) {
        log.info("开始结构化检索: query={}", query.getText());

        // 1. 查询分析
        AnalyzedQuery analyzedQuery = queryAnalyzer.analyze(query);
        log.debug("查询分析完成: intent={}, type={}",
                  analyzedQuery.getIntent(), analyzedQuery.getQueryType());

        // 2. 检索路由
        List<RetrievalPath> paths = retrievalRouter.route(analyzedQuery);
        log.debug("检索路由: paths={}", paths);

        // 3. 并行检索
        List<SearchResult> results = executeParallel(paths, analyzedQuery);
        log.debug("并行检索完成: 结果数={}", results.size());

        // 4. 结果融合
        List<SearchResult> merged = mergeResults(results);
        log.debug("结果融合完成: 合并后数量={}", merged.size());

        // 5. 重排序
        List<SearchResult> reranked = reranker.rerank(merged, query);
        log.debug("重排序完成");

        // 6. 上下文补全
        List<EnrichedResult> enriched = contextEnricher.enrich(
            reranked.subList(0, Math.min(config.getTopK(), reranked.size()))
        );
        log.debug("上下文补全完成");

        // 7. 构建返回结果
        return RetrievalResult.builder()
            .results(enriched)
            .totalCount(results.size())
            .returnedCount(enriched.size())
            .metadata(buildMetadata(analyzedQuery, paths))
            .build();
    }

    /**
     * 并行执行检索
     */
    private List<SearchResult> executeParallel(
            List<RetrievalPath> paths,
            AnalyzedQuery query) {

        // 使用CompletableFuture并行执行
        List<CompletableFuture<List<SearchResult>>> futures = paths.stream()
            .map(path -> CompletableFuture.supplyAsync(() -> {
                switch (path) {
                    case DOCUMENT_LEVEL:
                        return documentLevelRetrieval(query);
                    case CHAPTER_LEVEL:
                        return chapterLevelRetrieval(query);
                    case CHUNK_LEVEL:
                        return chunkLevelRetrieval(query);
                    case STRUCTURED:
                        return structuredRetrieval(query);
                    default:
                        return Collections.emptyList();
                }
            }))
            .collect(Collectors.toList());

        // 等待所有检索完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        // 合并结果
        return futures.stream()
            .flatMap(future -> future.join().stream())
            .collect(Collectors.toList());
    }

    /**
     * 章节级检索
     */
    private List<SearchResult> chapterLevelRetrieval(AnalyzedQuery query) {
        // 1. 向量化查询
        float[] queryVector = embeddingModel.embed(query.getText());

        // 2. 构建过滤表达式
        String filterExpr = buildFilterExpr(query);

        // 3. Milvus检索
        SearchParam searchParam = SearchParam.builder()
            .collectionName("kb_chapter_vectors")
            .vectorFieldName("vector")
            .vectors(Collections.singletonList(queryVector))
            .topK(10)
            .expr(filterExpr)
            .outputFields(Arrays.asList("node_id", "document_id", "level"))
            .build();

        List<QueryResultsWrapper.RowRecord> results = milvusClient.search(searchParam);

        // 4. 转换为SearchResult
        return results.stream()
            .map(this::convertToSearchResult)
            .collect(Collectors.toList());
    }

    /**
     * 结构化检索(基于类型)
     */
    private List<SearchResult> structuredRetrieval(AnalyzedQuery query) {
        List<SearchResult> results = new ArrayList<>();

        // 根据查询意图选择节点类型
        List<NodeType> targetTypes = determineTargetTypes(query.getIntent());

        for (NodeType type : targetTypes) {
            // 从数据库查询特定类型的节点
            List<DocumentNode> nodes = docNodeService.findByType(
                query.getDatasetId(),
                type
            );

            // 对每个节点计算相似度
            for (DocumentNode node : nodes) {
                double similarity = calculateSimilarity(query.getText(), node.getContent());
                if (similarity > 0.7) {  // 阈值
                    results.add(convertNodeToSearchResult(node, similarity));
                }
            }
        }

        return results;
    }

    /**
     * 确定目标节点类型
     */
    private List<NodeType> determineTargetTypes(QueryIntent intent) {
        switch (intent) {
            case LIST_QUERY:
                return Arrays.asList(NodeType.LIST, NodeType.TABLE);
            case CODE_QUERY:
                return Collections.singletonList(NodeType.CODE_BLOCK);
            case DEFINITION_QUERY:
                return Arrays.asList(NodeType.PARAGRAPH, NodeType.QUOTE);
            default:
                return Arrays.asList(NodeType.PARAGRAPH);
        }
    }
}

8.3 重排序策略 ​

java
/**
 * 重排序器
 */
@Component
@Slf4j
public class Reranker {

    /**
     * 重排序
     */
    public List<SearchResult> rerank(List<SearchResult> results, Query query) {
        // 计算综合分数
        results.forEach(result -> {
            double finalScore = calculateFinalScore(result, query);
            result.setFinalScore(finalScore);
        });

        // 按分数排序
        results.sort(Comparator.comparingDouble(SearchResult::getFinalScore).reversed());

        return results;
    }

    /**
     * 计算最终分数
     */
    private double calculateFinalScore(SearchResult result, Query query) {
        // 各个维度的分数
        double vectorScore = result.getVectorScore();              // 向量相似度 (0-1)
        double structureScore = calculateStructureScore(result);  // 结构分数 (0-1)
        double freshnessScore = calculateFreshnessScore(result); // 新鲜度 (0-1)
        double completenessScore = calculateCompletenessScore(result); // 完整性 (0-1)
        double relevanceScore = calculateRelevanceScore(result, query); // 相关性 (0-1)

        // 加权融合
        return 0.40 * vectorScore +           // 向量相似度权重最高
               0.20 * structureScore +        // 结构分数
               0.15 * completenessScore +     // 完整性
               0.15 * relevanceScore +        // 相关性
               0.10 * freshnessScore;         // 新鲜度
    }

    /**
     * 计算结构分数
     */
    private double calculateStructureScore(SearchResult result) {
        double score = 0.0;

        // 1. 完整章节得分更高
        if (result.getChunkType() == ChunkType.SECTION) {
            score += 0.3;
        }

        // 2. 有标题的得分更高
        if (StringUtils.isNotBlank(result.getTitle())) {
            score += 0.2;
        }

        // 3. 有摘要的得分更高
        if (StringUtils.isNotBlank(result.getSummary())) {
            score += 0.2;
        }

        // 4. 层级合适(不太深也不太浅)
        int level = result.getLevel();
        if (level >= 1 && level <= 3) {
            score += 0.3;
        } else if (level > 3) {
            score += 0.1;  // 太深的章节分数较低
        }

        return Math.min(score, 1.0);
    }

    /**
     * 计算完整性分数
     */
    private double calculateCompletenessScore(SearchResult result) {
        double score = 0.0;

        // 1. 内容长度(适中最好)
        int tokenCount = result.getTokenCount();
        if (tokenCount >= 200 && tokenCount <= 1000) {
            score += 0.4;  // 理想长度
        } else if (tokenCount < 200) {
            score += 0.2;  // 太短
        } else {
            score += 0.3;  // 太长
        }

        // 2. 是否包含上下文
        if (StringUtils.isNotBlank(result.getContextBefore())) {
            score += 0.2;
        }
        if (StringUtils.isNotBlank(result.getContextAfter())) {
            score += 0.2;
        }

        // 3. 是否有页码信息
        if (result.getPageNumber() != null) {
            score += 0.2;
        }

        return Math.min(score, 1.0);
    }

    /**
     * 计算相关性分数
     */
    private double calculateRelevanceScore(SearchResult result, Query query) {
        double score = 0.0;

        // 1. 标题匹配
        if (result.getTitle() != null &&
            containsKeywords(result.getTitle(), query.getKeywords())) {
            score += 0.4;
        }

        // 2. 内容关键词匹配
        int matchedKeywords = countMatchedKeywords(result.getContent(), query.getKeywords());
        score += Math.min(matchedKeywords * 0.1, 0.4);

        // 3. 实体匹配
        if (result.getMetadata() != null &&
            matchesEntities(result.getMetadata(), query.getEntities())) {
            score += 0.2;
        }

        return Math.min(score, 1.0);
    }
}

8.4 上下文补全 ​

java
/**
 * 上下文增强器
 */
@Component
@RequiredArgsConstructor
public class ContextEnricher {

    private final DocNodeService docNodeService;
    private final SmartChunkService smartChunkService;

    /**
     * 增强上下文
     */
    public List<EnrichedResult> enrich(List<SearchResult> results) {
        return results.stream()
            .map(this::enrichSingle)
            .collect(Collectors.toList());
    }

    /**
     * 增强单个结果
     */
    private EnrichedResult enrichSingle(SearchResult result) {
        // 1. 获取父章节信息
        ChapterContext chapterContext = getChapterContext(result);

        // 2. 获取相邻chunks
        List<Chunk> neighborChunks = getNeighborChunks(result);

        // 3. 构建完整上下文
        String fullContext = buildFullContext(result, chapterContext, neighborChunks);

        // 4. 生成引用信息
        Citation citation = buildCitation(result, chapterContext);

        return EnrichedResult.builder()
            .originalResult(result)
            .chapterContext(chapterContext)
            .neighborChunks(neighborChunks)
            .fullContext(fullContext)
            .citation(citation)
            .build();
    }

    /**
     * 获取章节上下文
     */
    private ChapterContext getChapterContext(SearchResult result) {
        // 如果结果本身就是章节,直接返回
        if (result.getNodeType() == NodeType.CHAPTER ||
            result.getNodeType() == NodeType.SECTION) {
            DocumentNode node = docNodeService.findById(result.getNodeId());
            return ChapterContext.fromNode(node);
        }

        // 否则,查找父章节
        List<DocumentNode> ancestors = docNodeService.findAncestors(result.getNodeId());

        // 找到最近的章节节点
        DocumentNode parentChapter = ancestors.stream()
            .filter(node -> node.getType() == NodeType.CHAPTER ||
                           node.getType() == NodeType.SECTION)
            .findFirst()
            .orElse(null);

        return parentChapter != null ?
            ChapterContext.fromNode(parentChapter) :
            ChapterContext.empty();
    }

    /**
     * 获取相邻chunks
     */
    private List<Chunk> getNeighborChunks(SearchResult result) {
        if (result.getChunkId() == null) {
            return Collections.emptyList();
        }

        // 获取前后各1个chunk
        Chunk currentChunk = smartChunkService.findById(result.getChunkId());
        List<Chunk> neighbors = new ArrayList<>();

        // 前一个chunk
        if (currentChunk.getChunkIndex() > 0) {
            Chunk prevChunk = smartChunkService.findByIndex(
                result.getDocumentId(),
                currentChunk.getChunkIndex() - 1
            );
            if (prevChunk != null) {
                neighbors.add(prevChunk);
            }
        }

        // 后一个chunk
        Chunk nextChunk = smartChunkService.findByIndex(
            result.getDocumentId(),
            currentChunk.getChunkIndex() + 1
        );
        if (nextChunk != null) {
            neighbors.add(nextChunk);
        }

        return neighbors;
    }

    /**
     * 构建完整上下文
     */
    private String buildFullContext(
            SearchResult result,
            ChapterContext chapterContext,
            List<Chunk> neighborChunks) {

        StringBuilder context = new StringBuilder();

        // 1. 添加章节路径和标题
        if (chapterContext != null && !chapterContext.isEmpty()) {
            context.append("# ").append(chapterContext.getTitle()).append("\n\n");
            if (StringUtils.isNotBlank(chapterContext.getSummary())) {
                context.append("> ").append(chapterContext.getSummary()).append("\n\n");
            }
        }

        // 2. 添加前文(如果有相邻chunk)
        if (!neighborChunks.isEmpty() && neighborChunks.get(0).getChunkIndex() < result.getChunkIndex()) {
            context.append("...(前文)...\n\n");
        }

        // 3. 添加主要内容
        context.append(result.getContent()).append("\n\n");

        // 4. 添加后文(如果有相邻chunk)
        if (neighborChunks.size() > 1) {
            context.append("...(后文)...\n\n");
        }

        return context.toString();
    }

    /**
     * 构建引用信息
     */
    private Citation buildCitation(SearchResult result, ChapterContext chapterContext) {
        return Citation.builder()
            .documentId(result.getDocumentId())
            .documentTitle(result.getDocumentTitle())
            .chapterPath(chapterContext != null ? chapterContext.getPath() : null)
            .chapterTitle(chapterContext != null ? chapterContext.getTitle() : null)
            .pageNumber(result.getPageNumber())
            .confidence(result.getFinalScore())
            .build();
    }
}

/**
 * 章节上下文
 */
@Data
@Builder
public class ChapterContext {
    private String path;          // 章节路径 (如 "1.2.3")
    private String title;         // 章节标题
    private String summary;       // 章节摘要
    private int level;            // 层级

    public static ChapterContext fromNode(DocumentNode node) {
        return ChapterContext.builder()
            .path(node.getPath())
            .title(node.getTitle())
            .summary(node.getMetadata().getAttribute("summary"))
            .level(node.getLevel())
            .build();
    }

    public static ChapterContext empty() {
        return ChapterContext.builder().build();
    }

    public boolean isEmpty() {
        return StringUtils.isBlank(title);
    }
}

/**
 * 引用信息
 */
@Data
@Builder
public class Citation {
    private Long documentId;
    private String documentTitle;
    private String chapterPath;
    private String chapterTitle;
    private Integer pageNumber;
    private Double confidence;

    /**
     * 格式化为引用文本
     */
    public String format() {
        StringBuilder citation = new StringBuilder();

        citation.append("[").append(documentTitle).append("]");

        if (StringUtils.isNotBlank(chapterPath)) {
            citation.append(" ").append(chapterPath);
        }

        if (StringUtils.isNotBlank(chapterTitle)) {
            citation.append(" ").append(chapterTitle);
        }

        if (pageNumber != null) {
            citation.append(", 第").append(pageNumber).append("页");
        }

        if (confidence != null) {
            citation.append(" (置信度: ").append(String.format("%.1f%%", confidence * 100)).append(")");
        }

        return citation.toString();
    }
}

9. 实施路线图 ​

9.1 整体规划 ​

时间线: 12-16周

Phase 1    Phase 2    Phase 3    Phase 4    Phase 5
  │          │          │          │          │
  ▼          ▼          ▼          ▼          ▼
基础设施   智能分块   多级向量化  结构化检索  兼容迁移
(2-3周)   (2-3周)    (2-3周)    (3-4周)    (1-2周)

9.2 Phase 1: 基础设施搭建 (2-3周) ​

目标 ​

搭建结构化RAG系统的基础设施和核心数据模型

任务清单 ​

Week 1-2: 数据库设计与实现

sql
-- 任务1: 创建数据表
✅ 创建 kb_doc_node 表(文档节点)
✅ 创建 kb_smart_chunk 表(智能分块)
✅ 创建 kb_vector_index 表(向量索引映射)
✅ 添加索引和约束
✅ 编写数据迁移脚本

-- 任务2: Milvus Collection设计
✅ 设计统一向量Collection schema
✅ 配置HNSW索引参数
✅ 创建Collection并测试

Week 2-3: 核心数据结构

java
// 任务3: 实现核心类
✅ DocumentTree 类及相关方法
✅ DocumentNode 类及层级关系
✅ NodeType、NodeMetadata枚举和类
✅ Chunk 类及ChunkType
✅ PageLocation、ChapterContext等辅助类

// 任务4: Mapper和Service
✅ DocNodeMapper、DocNodeService
✅ SmartChunkMapper、SmartChunkService
✅ VectorIndexMapper、VectorIndexService

验收标准 ​

  • [ ] 所有数据表创建成功,索引正常
  • [ ] Milvus Collection创建成功,可以插入和查询向量
  • [ ] 核心Java类单元测试覆盖率 > 80%
  • [ ] 可以保存和查询文档树结构

交付物 ​

  • 数据库迁移脚本 (V0.0.X__structured_rag.sql)
  • Milvus Collection创建脚本
  • 核心领域模型代码
  • 单元测试

9.3 Phase 2: 智能分块实现 (2-3周) ​

目标 ​

实现基于文档结构的智能分块策略

任务清单 ​

Week 1: 文档解析模块

java
// 任务1: DocumentParser接口和实现
✅ DocumentParser 接口定义
✅ MinerUParser 实现(核心)
✅ TikaParser 实现(后备)
✅ ParserConfig 配置类
✅ DocumentParserFactory 工厂类

// 任务2: MinerU集成
✅ 集成MinerU Python服务(HTTP API或进程调用)
✅ 实现Markdown解析(使用flexmark-java)
✅ 构建DocumentTree
✅ 提取图片、表格等资源

Week 2: 结构分析模块

java
// 任务3: StructureRecognizer
✅ 识别章节层级
✅ 识别章节编号
✅ 识别特殊结构(目录、参考文献、附录)

// 任务4: SemanticAnalyzer
✅ 提取章节摘要(使用LLM或传统方法)
✅ 识别主题和关键词
✅ 分类内容类型(定义、教程、示例等)

Week 3: 分块策略实现

java
// 任务5: ChunkingStrategy实现
✅ SectionBasedChunkingStrategy
✅ ParagraphBasedChunkingStrategy
✅ HybridChunkingStrategy(推荐)
✅ OverlapWindowGenerator(重叠窗口)
✅ ChunkingStrategyFactory

// 任务6: 配置和测试
✅ ChunkingConfig 配置类
✅ 分块质量评估工具
✅ 集成测试

验收标准 ​

  • [ ] MinerU可以成功解析PDF/Word文档
  • [ ] DocumentTree正确反映文档层级结构
  • [ ] 章节识别准确率 > 95%
  • [ ] 智能分块保持语义完整性
  • [ ] 分块大小在配置范围内(控制在±10%)
  • [ ] 单元测试覆盖率 > 80%

交付物 ​

  • DocumentParser模块代码
  • StructureAnalyzer模块代码
  • ChunkingStrategy模块代码
  • MinerU集成文档
  • 测试用例和测试报告

9.4 Phase 3: 多级向量化实现 (2-3周) ​

目标 ​

实现文档级、章节级、Chunk级的多级向量化

任务清单 ​

Week 1: 向量化引擎

java
// 任务1: MultiLevelVectorizationEngine
✅ 文档级向量化(摘要生成 + Embedding)
✅ 章节级向量化(章节内容 + Embedding)
✅ Chunk级向量化(批量Embedding)
✅ VectorizationResult 数据结构

// 任务2: 向量增强
✅ 层级关系编码
✅ 位置信息编码
✅ 类型标签编码

Week 2: 向量存储

java
// 任务3: Milvus存储优化
✅ 批量向量插入优化
✅ 向量索引管理
✅ Collection分区策略(按数据集分区)
✅ 向量压缩(可选,PQ/SQ)

// 任务4: VectorIndexService
✅ 向量ID映射管理
✅ 向量删除和更新
✅ 向量统计和监控

Week 3: 服务集成

java
// 任务5: StructuredVectorizationService
✅ 集成解析、分析、分块、向量化流程
✅ 事务管理
✅ 异常处理和重试
✅ 进度监控

// 任务6: 配置扩展
✅ StructuredVectorizationConfig
✅ 特殊元素向量化策略(表格、代码、图片)
✅ 质量控制配置

验收标准 ​

  • [ ] 多级向量化成功执行,三级向量都正确生成
  • [ ] 向量维度正确(根据Embedding模型)
  • [ ] Milvus存储成功,可以查询到向量
  • [ ] 向量化速度 < 5分钟/1000页
  • [ ] 向量索引映射正确
  • [ ] 错误处理和重试机制完善
  • [ ] 单元测试覆盖率 > 80%

交付物 ​

  • MultiLevelVectorizationEngine代码
  • StructuredVectorizationService代码
  • Milvus存储优化代码
  • 性能测试报告
  • 向量化配置文档

9.5 Phase 4: 结构化检索实现 (3-4周) ​

目标 ​

实现多路检索、结果融合、重排序、上下文补全

任务清单 ​

Week 1: 查询分析

java
// 任务1: QueryAnalyzer
✅ 意图识别(列表查询、定义查询、代码查询等)
✅ 实体识别
✅ 查询类型分类
✅ 关键词提取

// 任务2: RetrievalRouter
✅ 路由策略配置
✅ 多路径选择逻辑
✅ 路径权重配置

Week 2: 多路检索

java
// 任务3: 实现检索路径
✅ 文档级检索(DocumentLevelRetrieval)
✅ 章节级检索(ChapterLevelRetrieval)
✅ Chunk级检索(ChunkLevelRetrieval)
✅ 结构化检索(StructuredRetrieval)

// 任务4: 并行执行
✅ CompletableFuture并行查询
✅ 超时控制
✅ 异常处理

Week 3: 结果处理

java
// 任务5: Reranker
✅ 多维度评分(向量、结构、完整性、相关性、新鲜度)
✅ 加权融合策略
✅ 去重逻辑
✅ TopK选择

// 任务6: ContextEnricher
✅ 父章节上下文获取
✅ 相邻Chunk获取
✅ 完整上下文构建
✅ Citation生成

Week 4: 服务集成和优化

java
// 任务7: StructuredRetrievalService
✅ 集成查询分析、路由、检索、重排序、上下文补全
✅ RetrievalConfig配置
✅ 检索结果缓存(可选)
✅ 性能监控

// 任务8: API接口
✅ 检索REST API
✅ 请求参数验证
✅ 响应格式标准化
✅ API文档(Swagger)

验收标准 ​

  • [ ] 多路检索正确执行,所有路径都能返回结果
  • [ ] 重排序提升检索准确率 > 10%
  • [ ] 上下文补全正确,包含父章节和相邻内容
  • [ ] Citation格式正确,信息完整
  • [ ] 检索延迟 < 500ms (P95)
  • [ ] 检索准确率 > 85%(人工评测)
  • [ ] API文档完整

交付物 ​

  • QueryAnalyzer和RetrievalRouter代码
  • 多路检索实现代码
  • Reranker和ContextEnricher代码
  • StructuredRetrievalService代码
  • REST API代码
  • API文档
  • 检索性能测试报告
  • 准确率评测报告

9.6 Phase 5: 向后兼容与迁移 (1-2周) ​

目标 ​

确保向后兼容,支持渐进式迁移

任务清单 ​

Week 1: 兼容性实现

java
// 任务1: 配置化切换
✅ 数据集级别的向量化策略配置
✅ 支持新旧两种向量化方式共存
✅ 配置热更新(可选)

// 任务2: API兼容
✅ 保留现有API接口
✅ 新旧检索结果格式统一
✅ 降级策略(新系统失败时回退到旧系统)

// 任务3: 数据迁移工具
✅ 旧数据评估工具(统计chunk数量、token分布)
✅ 增量迁移工具(逐个文档迁移)
✅ 批量迁移工具(数据集级别迁移)
✅ 迁移进度监控

Week 2: 灰度发布和验证

java
// 任务4: 灰度发布
✅ A/B测试框架(部分用户使用新系统)
✅ 效果对比(准确率、延迟、用户满意度)
✅ 监控报警

// 任务5: 文档和培训
✅ 迁移指南
✅ 配置说明文档
✅ 常见问题FAQ
✅ 团队培训材料

验收标准 ​

  • [ ] 新旧系统可以共存
  • [ ] 配置切换正常,无需重启服务
  • [ ] 迁移工具测试通过,无数据丢失
  • [ ] 灰度发布无重大故障
  • [ ] 新系统准确率 > 旧系统准确率
  • [ ] 文档齐全

交付物 ​

  • 配置化切换代码
  • API兼容层代码
  • 数据迁移工具
  • 灰度发布脚本
  • 迁移指南
  • 用户文档

9.7 项目里程碑 ​

里程碑1 (Week 3)
└─ 基础设施就绪
   ├─ 数据库表创建完成
   ├─ Milvus Collection配置完成
   └─ 核心数据结构实现

里程碑2 (Week 6)
└─ 智能分块可用
   ├─ MinerU集成成功
   ├─ 文档树构建正确
   └─ 分块策略实现

里程碑3 (Week 9)
└─ 多级向量化完成
   ├─ 三级向量化成功
   ├─ 向量存储优化
   └─ 服务集成测试通过

里程碑4 (Week 13)
└─ 结构化检索上线
   ├─ 多路检索实现
   ├─ 重排序和上下文补全
   └─ API接口发布

里程碑5 (Week 15)
└─ 生产环境就绪
   ├─ 向后兼容实现
   ├─ 数据迁移完成
   └─ 灰度发布成功

10. 技术选型 ​

10.1 文档解析工具 ​

对比表格 ​

工具优势劣势推荐度备注
MinerU⭐⭐⭐⭐⭐
• 专为RAG优化
• 保留完整结构
• 识别章节层级
• 提取图表和公式
• 输出结构化Markdown
• 需要额外部署
• 依赖Python环境
推荐最适合本项目
Apache Tika⭐⭐⭐
• Java原生
• 支持多种格式
• 社区成熟
• 丢失文档结构
• 只提取纯文本
• 无法识别章节
后备方案可作为降级选项
PyPDF2⭐⭐
• 轻量级
• 易于集成
• 功能有限
• PDF解析质量一般
• 不支持Word
不推荐功能不足
PDFBox⭐⭐⭐
• Java原生
• PDF解析能力强
• 只支持PDF
• 丢失结构信息
可选仅PDF场景可用

最终选择: MinerU ​

理由:

  1. 结构保留: MinerU是唯一能保留文档完整层级结构的工具
  2. 专为RAG设计: 输出的Markdown格式非常适合RAG应用
  3. 质量高: 对章节、表格、图片的识别准确率高
  4. 可扩展: 支持自定义解析规则

集成方案:

java
// 方案1: HTTP API调用(推荐)
// 部署MinerU服务,通过REST API调用
MinerUClient client = new MinerUClient("http://localhost:8000");
MinerUResult result = client.parse("/path/to/document.pdf");

// 方案2: 进程调用
// 直接调用Python脚本
ProcessBuilder pb = new ProcessBuilder("python", "mineru_parse.py", filePath);
Process process = pb.start();

10.2 Markdown解析器 ​

对比表格 ​

工具优势劣势推荐度
Flexmark-java⭐⭐⭐⭐⭐
• 功能强大
• 可扩展
• AST支持
• 活跃维护
• 学习曲线略陡推荐
CommonMark-java⭐⭐⭐⭐
• 符合标准
• 简单易用
• 扩展性较差可选
MarkdownJ⭐⭐
• 轻量级
• 功能有限
• 不再维护
不推荐

最终选择: Flexmark-java ​

示例代码:

java
// 解析Markdown并构建文档树
Parser parser = Parser.builder().build();
Node document = parser.parse(markdownContent);

// 遍历AST
document.accept(new AbstractVisitor() {
    @Override
    public void visit(Heading heading) {
        int level = heading.getLevel();  // H1-H6
        String text = heading.getChars().toString();
        // 创建章节节点
    }

    @Override
    public void visit(Paragraph paragraph) {
        // 创建段落节点
    }

    @Override
    public void visit(BulletList list) {
        // 创建列表节点
    }
});

10.3 语义分析方法 ​

方案对比 ​

方案实现方式准确率成本延迟推荐场景
LLM摘要调用GPT/Claude生成章节摘要⭐⭐⭐⭐⭐ 95%+高高高质量要求
Extractive摘要TextRank/LexRank算法⭐⭐⭐ 75%低低成本敏感
规则分类正则+关键词⭐⭐⭐ 70%低低简单场景
BERT分类Fine-tuned BERT⭐⭐⭐⭐ 85%中中平衡方案

推荐组合方案 ​

java
public class HybridSemanticAnalyzer {

    /**
     * 混合语义分析
     */
    public void analyze(DocumentTree tree) {
        tree.traverse(node -> {
            if (node.getType() == NodeType.CHAPTER) {
                // 重要章节:使用LLM生成高质量摘要
                if (isImportantChapter(node)) {
                    String summary = llmClient.generateSummary(node.getContent());
                    node.getMetadata().setAttribute("summary", summary);
                } else {
                    // 一般章节:使用TextRank提取式摘要
                    String summary = textRankSummarizer.summarize(node.getContent());
                    node.getMetadata().setAttribute("summary", summary);
                }
            }

            // 内容分类:使用规则+BERT
            if (node.getType() == NodeType.PARAGRAPH) {
                // 先用规则快速分类
                ContentType type = ruleClassifier.classify(node.getContent());

                // 规则不确定时,使用BERT
                if (type == ContentType.UNKNOWN) {
                    type = bertClassifier.classify(node.getContent());
                }

                node.getMetadata().setAttribute("contentType", type.name());
            }
        });
    }
}

10.4 向量数据库 ​

对比表格 ​

数据库优势劣势适用场景
Milvus⭐⭐⭐⭐⭐
• 性能优秀
• 功能丰富
• 支持多种索引
• 活跃社区
• 部署相对复杂推荐
生产环境
Qdrant⭐⭐⭐⭐
• Rust实现,性能好
• 易部署
• 社区较小中小规模
Weaviate⭐⭐⭐⭐
• 集成度高
• GraphQL查询
• 资源占用大集成需求高
Pinecone⭐⭐⭐⭐
• 全托管
• 易用性好
• 成本高
• 依赖云服务
快速上线
FAISS⭐⭐⭐
• Facebook出品
• 性能好
• 功能有限
• 需自行封装
实验/原型

最终选择: Milvus ​

理由:

  • 已有集成基础(项目中已使用)
  • 性能满足要求(支持10亿+向量)
  • HNSW索引适合高维向量检索
  • 支持标量字段过滤(重要!)

索引配置:

python
# HNSW索引配置(推荐)
index_params = {
    "metric_type": "COSINE",
    "index_type": "HNSW",
    "params": {
        "M": 16,              # 每层连接数(越大精度越高,内存越大)
        "efConstruction": 200 # 构建时搜索深度(影响构建时间)
    }
}

# 查询参数
search_params = {
    "metric_type": "COSINE",
    "params": {
        "ef": 64  # 查询时搜索深度(越大精度越高,延迟越大)
    }
}

10.5 Embedding模型 ​

模型对比 ​

模型维度准确率速度成本推荐场景
OpenAI text-embedding-3-large3072⭐⭐⭐⭐⭐快高高质量要求
OpenAI text-embedding-3-small1536⭐⭐⭐⭐快中推荐
智谱 embedding-21536⭐⭐⭐⭐快中中文场景
BGE-large-zh1024⭐⭐⭐⭐中低本地部署
M3E-large1024⭐⭐⭐中低中文+成本敏感

推荐选择 ​

生产环境: OpenAI text-embedding-3-small

  • 性价比最佳
  • 1536维适中
  • 中英文效果好

成本敏感: BGE-large-zh (本地部署)

  • 免费
  • 中文效果好
  • 可GPU加速

11. 性能优化 ​

11.1 解析性能优化 ​

优化策略 ​

1. 并行解析

java
@Service
public class ParallelDocumentParser {

    private final ExecutorService executor = Executors.newFixedThreadPool(4);

    /**
     * 批量并行解析
     */
    public List<DocumentTree> parseBatch(List<RawDocument> documents) {
        List<CompletableFuture<DocumentTree>> futures = documents.stream()
            .map(doc -> CompletableFuture.supplyAsync(
                () -> parser.parse(doc, config),
                executor
            ))
            .collect(Collectors.toList());

        return futures.stream()
            .map(CompletableFuture::join)
            .collect(Collectors.toList());
    }
}

2. 结果缓存

java
@Service
public class CachedDocumentParser {

    @Cacheable(value = "documentTrees", key = "#document.hash")
    public DocumentTree parse(RawDocument document, ParserConfig config) {
        // 如果文档内容未变,直接返回缓存的DocumentTree
        return actualParser.parse(document, config);
    }
}

3. 分页解析大文档

java
public class StreamingDocumentParser {

    /**
     * 流式解析大文档(避免OOM)
     */
    public DocumentTree parseLargeDocument(RawDocument document) {
        DocumentTree tree = new DocumentTree();

        // 按页分批处理
        int pageSize = 50;  // 每批50页
        for (int page = 0; page < document.getTotalPages(); page += pageSize) {
            // 解析部分页面
            List<DocumentNode> nodes = parsePages(document, page, page + pageSize);
            tree.addNodes(nodes);

            // 释放中间对象
            System.gc();
        }

        return tree;
    }
}

性能指标 ​

文档大小优化前优化后提升
100页45s12s73% ↓
500页240s58s76% ↓
1000页520s115s78% ↓

11.2 向量化性能优化 ​

优化策略 ​

1. 批量Embedding

java
public class BatchEmbeddingOptimizer {

    /**
     * 批量向量化(减少API调用次数)
     */
    public List<ChunkVector> vectorizeChunks(List<Chunk> chunks) {
        int batchSize = 100;  // 每批100个
        List<ChunkVector> results = new ArrayList<>();

        for (int i = 0; i < chunks.size(); i += batchSize) {
            List<Chunk> batch = chunks.subList(
                i,
                Math.min(i + batchSize, chunks.size())
            );

            // 批量调用Embedding API
            List<String> contents = batch.stream()
                .map(Chunk::getContent)
                .collect(Collectors.toList());

            List<float[]> vectors = embeddingModel.embedBatch(contents);

            // 组装结果
            for (int j = 0; j < batch.size(); j++) {
                results.add(ChunkVector.builder()
                    .chunkId(batch.get(j).getId())
                    .vector(vectors.get(j))
                    .build());
            }
        }

        return results;
    }
}

2. 异步向量化

java
@Service
public class AsyncVectorizationService {

    @Async("vectorizationExecutor")
    public CompletableFuture<VectorizationResult> vectorizeAsync(Long documentId) {
        VectorizationResult result = vectorizeDocument(documentId);
        return CompletableFuture.completedFuture(result);
    }

    // 配置线程池
    @Bean(name = "vectorizationExecutor")
    public ThreadPoolTaskExecutor vectorizationExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("vectorization-");
        executor.initialize();
        return executor;
    }
}

3. Milvus批量插入优化

java
public class OptimizedMilvusInsertion {

    /**
     * 批量插入向量(提升吞吐量)
     */
    public void batchInsert(List<ChunkVector> vectors) {
        int batchSize = 1000;  // 每批1000条

        for (int i = 0; i < vectors.size(); i += batchSize) {
            List<ChunkVector> batch = vectors.subList(
                i,
                Math.min(i + batchSize, vectors.size())
            );

            // 构建插入数据
            List<InsertParam.Field> fields = buildFields(batch);

            // 批量插入
            InsertParam insertParam = InsertParam.newBuilder()
                .withCollectionName(collectionName)
                .withFields(fields)
                .build();

            milvusClient.insert(insertParam);
        }

        // 插入完成后,刷新确保数据可查询
        milvusClient.flush(collectionName);
    }
}

4. 向量压缩(可选)

python
# 使用PQ (Product Quantization) 压缩向量
index_params = {
    "metric_type": "COSINE",
    "index_type": "IVF_PQ",    # 使用PQ压缩
    "params": {
        "nlist": 1024,         # 聚类中心数
        "m": 8,                # 子向量数量(压缩率 = dimension / m)
        "nbits": 8             # 每个子向量的位数
    }
}

# 效果:
# - 存储空间减少 75%
# - 查询速度提升 50%
# - 准确率轻微下降 2-3%

性能指标 ​

优化项优化前优化后提升
1000个chunk向量化120s25s79% ↓
Milvus插入(10万条)180s35s81% ↓
存储空间(100万向量)6GB1.5GB75% ↓

11.3 检索性能优化 ​

优化策略 ​

1. 查询结果缓存

java
@Service
public class CachedRetrievalService {

    @Cacheable(
        value = "retrievalResults",
        key = "#query.text + '-' + #config.topK",
        condition = "#query.cacheable == true"
    )
    public RetrievalResult retrieve(Query query, RetrievalConfig config) {
        return actualRetrievalService.retrieve(query, config);
    }

    // 缓存配置
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("retrievalResults");
        cacheManager.setCaffeine(Caffeine.newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)  // 10分钟过期
            .maximumSize(1000));                     // 最多1000条
        return cacheManager;
    }
}

2. Milvus查询优化

java
public class OptimizedMilvusSearch {

    /**
     * 优化Milvus查询参数
     */
    public List<SearchResult> search(float[] queryVector, int topK) {
        SearchParam searchParam = SearchParam.newBuilder()
            .withCollectionName(collectionName)
            .withVectorFieldName("vector")
            .withVectors(Collections.singletonList(queryVector))
            .withTopK(topK)

            // 关键优化:调整ef参数
            .withParams("{\"ef\": 64}")  // 默认值,可根据准确率要求调整

            // 使用标量过滤减少搜索空间
            .withExpr("dataset_id == " + datasetId)

            // 只返回必要字段
            .withOutFields(Arrays.asList("entity_id", "entity_type"))

            .build();

        return milvusClient.search(searchParam);
    }
}

3. 分层检索优化

java
public class HierarchicalRetrievalOptimizer {

    /**
     * 分层检索:先粗后精
     */
    public List<EnrichedResult> hierarchicalRetrieve(Query query) {
        // Step 1: 章节级检索(粗粒度,快速)
        List<SearchResult> chapterResults = chapterLevelRetrieval(query, 20);

        if (chapterResults.isEmpty()) {
            return Collections.emptyList();
        }

        // Step 2: 在相关章节内进行Chunk级检索(细粒度,精确)
        Set<Long> relevantChapterIds = chapterResults.stream()
            .map(SearchResult::getNodeId)
            .collect(Collectors.toSet());

        List<SearchResult> chunkResults = chunkLevelRetrievalInChapters(
            query,
            relevantChapterIds,
            10
        );

        // Step 3: 重排序和上下文补全
        return postProcess(chunkResults);
    }
}

4. 预计算和索引

sql
-- 为常用查询字段创建索引
CREATE INDEX idx_chunk_chapter_path ON kb_smart_chunk(chapter_path);
CREATE INDEX idx_node_path ON kb_doc_node(path);

-- 预计算章节摘要(避免每次查询时生成)
ALTER TABLE kb_doc_node ADD COLUMN summary_vector BLOB;

-- 定期更新摘要向量
UPDATE kb_doc_node
SET summary_vector = VECTOR_FROM_TEXT(summary)
WHERE summary IS NOT NULL;

性能指标 ​

优化项P50P95P99
检索延迟(优化前)450ms1200ms2500ms
检索延迟(优化后)180ms420ms850ms
提升60% ↓65% ↓66% ↓

11.4 存储优化 ​

优化策略 ​

1. 分区策略

python
# Milvus按数据集分区
collection.create_partition("dataset_1")
collection.create_partition("dataset_2")

# 查询时指定分区,减少搜索空间
search_params = {
    "partition_names": ["dataset_1"],  # 只搜索特定分区
    "params": {"ef": 64}
}

2. 数据压缩

sql
-- 对大字段启用压缩
ALTER TABLE kb_smart_chunk
MODIFY COLUMN content TEXT COMPRESSED;

ALTER TABLE kb_smart_chunk
MODIFY COLUMN context_before TEXT COMPRESSED;

3. 冷热数据分离

java
@Service
public class DataArchivalService {

    /**
     * 归档旧数据
     */
    @Scheduled(cron = "0 0 2 * * ?")  // 每天凌晨2点
    public void archiveOldData() {
        // 查询6个月前的数据
        LocalDateTime archiveDate = LocalDateTime.now().minusMonths(6);

        List<KbSmartChunk> oldChunks = smartChunkService.list(
            new LambdaQueryWrapper<KbSmartChunk>()
                .lt(KbSmartChunk::getCreateTime, archiveDate)
        );

        if (!oldChunks.isEmpty()) {
            // 导出到归档存储(如S3)
            archiveStorage.save(oldChunks);

            // 从主库删除
            smartChunkService.removeBatchByIds(
                oldChunks.stream()
                    .map(KbSmartChunk::getId)
                    .collect(Collectors.toList())
            );

            // 从Milvus删除向量
            String expr = buildExprForOldChunks(oldChunks);
            embeddingStore.remove(expr);
        }
    }
}

12. 向后兼容 ​

12.1 兼容性策略 ​

核心原则 ​

  1. 新旧共存: 两种向量化方式可以同时存在
  2. 配置驱动: 通过配置选择使用哪种方式
  3. 无缝切换: 切换过程对用户透明
  4. 可回退: 新方案有问题时可快速回退

12.2 配置化切换 ​

数据集级别配置 ​

java
/**
 * 数据集配置(扩展)
 */
@Data
public class KbDatasetEntity {
    // ... 现有字段

    /**
     * 向量化策略: LEGACY (传统固定分块) / STRUCTURED (结构化)
     */
    private VectorizationStrategy vectorizationStrategy = VectorizationStrategy.LEGACY;

    /**
     * 检索策略: SIMPLE (简单向量检索) / STRUCTURED (结构化检索)
     */
    private RetrievalStrategy retrievalStrategy = RetrievalStrategy.SIMPLE;
}

public enum VectorizationStrategy {
    LEGACY,      // 传统方式(固定大小分块)
    STRUCTURED   // 结构化方式(智能分块)
}

public enum RetrievalStrategy {
    SIMPLE,      // 简单向量检索
    STRUCTURED   // 结构化检索(多路、重排序等)
}

向量化服务路由 ​

java
@Service
public class VectorizationServiceRouter {

    private final VectorizationService legacyService;           // 旧服务
    private final StructuredVectorizationService structuredService;  // 新服务
    private final KbDatasetService datasetService;

    /**
     * 根据数据集配置路由到不同的向量化服务
     */
    public VectorizationResult vectorizeDocument(Long documentId) {
        // 获取文档所属数据集
        KbDocumentEntity document = kbDocumentService.getById(documentId);
        KbDatasetEntity dataset = datasetService.getById(document.getDatasetId());

        // 根据策略选择服务
        if (dataset.getVectorizationStrategy() == VectorizationStrategy.STRUCTURED) {
            log.info("使用结构化向量化: documentId={}", documentId);
            return structuredService.vectorize(documentId);
        } else {
            log.info("使用传统向量化: documentId={}", documentId);
            return legacyService.vectorizeDocument(documentId);
        }
    }
}

检索服务路由 ​

java
@Service
public class RetrievalServiceRouter {

    private final SimpleRetrievalService simpleService;         // 旧检索
    private final StructuredRetrievalService structuredService; // 新检索

    /**
     * 根据数据集配置路由检索请求
     */
    public RetrievalResult retrieve(Long datasetId, String query) {
        KbDatasetEntity dataset = datasetService.getById(datasetId);

        if (dataset.getRetrievalStrategy() == RetrievalStrategy.STRUCTURED) {
            log.info("使用结构化检索: datasetId={}, query={}", datasetId, query);
            return structuredService.retrieve(
                Query.builder().text(query).datasetId(datasetId).build(),
                RetrievalConfig.getDefault()
            );
        } else {
            log.info("使用简单检索: datasetId={}, query={}", datasetId, query);
            return simpleService.retrieve(datasetId, query);
        }
    }
}

12.3 API兼容层 ​

统一响应格式 ​

java
/**
 * 统一检索响应(兼容新旧两种结果)
 */
@Data
@Builder
public class UnifiedRetrievalResponse {
    // 基础字段(新旧共有)
    private List<RetrievalItem> items;
    private Integer totalCount;
    private Long durationMs;

    // 扩展字段(仅新系统)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private RetrievalMetadata metadata;  // 检索元数据(路径、权重等)

    /**
     * 从简单检索结果转换
     */
    public static UnifiedRetrievalResponse fromSimple(SimpleRetrievalResult result) {
        return UnifiedRetrievalResponse.builder()
            .items(result.getChunks().stream()
                .map(chunk -> RetrievalItem.builder()
                    .content(chunk.getContent())
                    .score(chunk.getScore())
                    .documentId(chunk.getDocumentId())
                    .build())
                .collect(Collectors.toList()))
            .totalCount(result.getTotalCount())
            .build();
    }

    /**
     * 从结构化检索结果转换
     */
    public static UnifiedRetrievalResponse fromStructured(RetrievalResult result) {
        return UnifiedRetrievalResponse.builder()
            .items(result.getResults().stream()
                .map(enriched -> RetrievalItem.builder()
                    .content(enriched.getFullContext())  // 完整上下文
                    .score(enriched.getOriginalResult().getFinalScore())
                    .documentId(enriched.getOriginalResult().getDocumentId())
                    // 扩展字段
                    .title(enriched.getChapterContext().getTitle())
                    .chapterPath(enriched.getChapterContext().getPath())
                    .citation(enriched.getCitation().format())
                    .build())
                .collect(Collectors.toList()))
            .totalCount(result.getTotalCount())
            .metadata(result.getMetadata())
            .build();
    }
}

REST API兼容 ​

java
@RestController
@RequestMapping("/api/v1/retrieval")
public class RetrievalController {

    private final RetrievalServiceRouter retrievalRouter;

    /**
     * 统一检索接口(自动路由)
     */
    @PostMapping("/search")
    public R<UnifiedRetrievalResponse> search(@RequestBody SearchRequest request) {
        // 路由到相应的检索服务
        Object result = retrievalRouter.retrieve(request.getDatasetId(), request.getQuery());

        // 转换为统一格式
        UnifiedRetrievalResponse response;
        if (result instanceof SimpleRetrievalResult) {
            response = UnifiedRetrievalResponse.fromSimple((SimpleRetrievalResult) result);
        } else {
            response = UnifiedRetrievalResponse.fromStructured((RetrievalResult) result);
        }

        return R.ok(response);
    }
}

12.4 数据迁移策略 ​

渐进式迁移 ​

java
@Service
public class GradualMigrationService {

    /**
     * 渐进式迁移:每次迁移部分文档
     */
    @Transactional(rollbackFor = Exception.class)
    public MigrationResult migrateDataset(Long datasetId, MigrationConfig config) {
        log.info("开始渐进式迁移: datasetId={}", datasetId);

        // 1. 查询该数据集下所有文档
        List<KbDocumentEntity> documents = kbDocumentService.list(
            new LambdaQueryWrapper<KbDocumentEntity>()
                .eq(KbDocumentEntity::getDatasetId, datasetId)
        );

        int successCount = 0;
        int failCount = 0;

        // 2. 逐个迁移文档
        for (KbDocumentEntity document : documents) {
            try {
                // 检查是否已迁移
                if (isMigrated(document.getId())) {
                    log.info("文档已迁移,跳过: documentId={}", document.getId());
                    continue;
                }

                // 执行迁移
                migrateDocument(document.getId());
                successCount++;

                // 标记已迁移
                markAsMigrated(document.getId());

                // 限速:避免过载
                if (config.getDelayMs() > 0) {
                    Thread.sleep(config.getDelayMs());
                }

            } catch (Exception e) {
                log.error("文档迁移失败: documentId={}", document.getId(), e);
                failCount++;
            }
        }

        // 3. 迁移完成后,更新数据集配置
        if (failCount == 0) {
            KbDatasetEntity dataset = kbDatasetService.getById(datasetId);
            dataset.setVectorizationStrategy(VectorizationStrategy.STRUCTURED);
            dataset.setRetrievalStrategy(RetrievalStrategy.STRUCTURED);
            kbDatasetService.updateById(dataset);

            log.info("数据集迁移完成,已切换到结构化模式: datasetId={}", datasetId);
        }

        return MigrationResult.builder()
            .totalDocuments(documents.size())
            .successCount(successCount)
            .failCount(failCount)
            .build();
    }

    /**
     * 迁移单个文档
     */
    private void migrateDocument(Long documentId) {
        log.info("迁移文档: documentId={}", documentId);

        // 1. 删除旧的chunk和向量
        deleteOldChunksAndVectors(documentId);

        // 2. 使用结构化方式重新向量化
        structuredVectorizationService.vectorize(documentId);

        log.info("文档迁移成功: documentId={}", documentId);
    }

    /**
     * 删除旧的chunk和向量
     */
    private void deleteOldChunksAndVectors(Long documentId) {
        // 删除kb_chunk表中的数据
        kbChunkService.remove(
            new LambdaQueryWrapper<KbChunkEntity>()
                .eq(KbChunkEntity::getDocumentId, documentId)
        );

        // 删除Milvus中的向量
        String expr = String.format("documentId == '%s'", documentId);
        embeddingStore.remove(expr);
    }
}

迁移状态追踪 ​

sql
-- 迁移状态表
CREATE TABLE `kb_migration_status` (
    `id` BIGINT NOT NULL,
    `document_id` BIGINT NOT NULL COMMENT '文档ID',
    `dataset_id` BIGINT NOT NULL COMMENT '数据集ID',
    `migration_status` VARCHAR(20) NOT NULL COMMENT '迁移状态: PENDING/MIGRATING/SUCCESS/FAILED',
    `old_chunk_count` INT NULL COMMENT '旧chunk数量',
    `new_chunk_count` INT NULL COMMENT '新chunk数量',
    `error_message` TEXT NULL COMMENT '错误信息',
    `migrated_at` DATETIME NULL COMMENT '迁移时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_document_id` (`document_id`),
    KEY `idx_dataset_id` (`dataset_id`),
    KEY `idx_status` (`migration_status`)
) COMMENT='迁移状态表';

12.5 降级策略 ​

自动降级 ​

java
@Service
public class FallbackRetrievalService {

    private final StructuredRetrievalService structuredService;
    private final SimpleRetrievalService simpleService;

    /**
     * 带降级的检索(结构化失败时自动降级到简单检索)
     */
    public RetrievalResult retrieveWithFallback(Query query) {
        try {
            // 尝试结构化检索
            return structuredService.retrieve(query, RetrievalConfig.getDefault());

        } catch (Exception e) {
            log.error("结构化检索失败,降级到简单检索: query={}", query.getText(), e);

            // 降级到简单检索
            SimpleRetrievalResult simpleResult = simpleService.retrieve(
                query.getDatasetId(),
                query.getText()
            );

            // 转换为统一格式
            return convertToRetrievalResult(simpleResult);
        }
    }
}

手动切换 ​

java
@RestController
@RequestMapping("/api/v1/admin/dataset")
public class DatasetAdminController {

    /**
     * 切换数据集的向量化策略
     */
    @PostMapping("/{datasetId}/switch-vectorization-strategy")
    public R<Void> switchVectorizationStrategy(
            @PathVariable Long datasetId,
            @RequestParam VectorizationStrategy strategy) {

        KbDatasetEntity dataset = kbDatasetService.getById(datasetId);
        dataset.setVectorizationStrategy(strategy);
        kbDatasetService.updateById(dataset);

        log.info("数据集向量化策略已切换: datasetId={}, strategy={}", datasetId, strategy);
        return R.ok();
    }
}

13. 风险评估与应对 ​

13.1 技术风险 ​

风险1: MinerU解析失败 ​

风险描述: MinerU可能无法正确解析某些复杂PDF(如扫描件、图片PDF)

影响: 文档树构建失败,无法进行结构化向量化

概率: 中 (10-20%)

应对措施:

java
@Service
public class RobustDocumentParser {

    private final MinerUParser minerUParser;
    private final TikaParser tikaParser;  // 后备解析器

    /**
     * 带后备的文档解析
     */
    public DocumentTree parseWithFallback(RawDocument document) {
        try {
            // 优先使用MinerU
            return minerUParser.parse(document, ParserConfig.getDefault());

        } catch (ParseException e) {
            log.warn("MinerU解析失败,使用Tika后备解析: document={}", document.getName(), e);

            // 降级到Tika(丢失结构,但至少能提取文本)
            DocumentTree tree = tikaParser.parse(document, ParserConfig.getDefault());

            // 标记为降级解析
            tree.getMetadata().setAttribute("parsedBy", "Tika");
            tree.getMetadata().setAttribute("structurePreserved", "false");

            return tree;
        }
    }
}

风险2: 大文档OOM ​

风险描述: 处理超大文档(如1000页+)时可能内存溢出

影响: 服务崩溃

概率: 低 (< 5%)

应对措施:

java
@Service
public class MemorySafeDocumentProcessor {

    private static final int MAX_DOCUMENT_SIZE_MB = 100;  // 最大100MB
    private static final int MAX_PAGES = 2000;            // 最大2000页

    /**
     * 内存安全的文档处理
     */
    public DocumentTree processLargeDocument(RawDocument document) {
        // 检查文档大小
        if (document.getSizeInMB() > MAX_DOCUMENT_SIZE_MB) {
            throw new DocumentTooLargeException(
                String.format("文档过大: %dMB > %dMB",
                    document.getSizeInMB(), MAX_DOCUMENT_SIZE_MB)
            );
        }

        // 检查页数
        if (document.getTotalPages() > MAX_PAGES) {
            // 分片处理
            return processInChunks(document);
        } else {
            // 正常处理
            return parser.parse(document, ParserConfig.getDefault());
        }
    }

    /**
     * 分片处理大文档
     */
    private DocumentTree processInChunks(RawDocument document) {
        int chunkSize = 200;  // 每次处理200页
        DocumentTree tree = new DocumentTree();

        for (int page = 0; page < document.getTotalPages(); page += chunkSize) {
            // 提取部分页面
            RawDocument chunk = document.extractPages(page, page + chunkSize);

            // 解析
            DocumentTree chunkTree = parser.parse(chunk, ParserConfig.getDefault());

            // 合并
            tree.merge(chunkTree);

            // 强制GC
            System.gc();
        }

        return tree;
    }
}

风险3: Milvus性能瓶颈 ​

风险描述: 向量数据量增长后Milvus查询变慢

影响: 检索延迟增加,用户体验下降

概率: 中 (20-30%)

应对措施:

  1. 监控和预警
java
@Component
public class MilvusPerformanceMonitor {

    @Scheduled(fixedRate = 60000)  // 每分钟检查
    public void monitorPerformance() {
        // 查询统计信息
        CollectionStats stats = milvusClient.getCollectionStats(collectionName);

        long rowCount = stats.getRowCount();
        long indexSize = stats.getIndexSize();

        // 检查阈值
        if (rowCount > 10_000_000) {  // 超过1000万条
            log.warn("Milvus数据量过大: rowCount={}", rowCount);
            alertService.send("Milvus数据量告警", "建议分区或归档");
        }

        // 记录指标
        metrics.recordGauge("milvus.row_count", rowCount);
        metrics.recordGauge("milvus.index_size_mb", indexSize / 1024 / 1024);
    }
}
  1. 分区策略
python
# 按数据集和时间分区
partition_name = f"dataset_{dataset_id}_2024Q1"
collection.create_partition(partition_name)

# 查询时指定分区
search_params = {
    "partition_names": [partition_name],
    "params": {"ef": 64}
}
  1. 索引优化
python
# 使用更快的索引(牺牲少量准确率)
index_params = {
    "metric_type": "COSINE",
    "index_type": "IVF_FLAT",  # 比HNSW更快,但准确率略低
    "params": {"nlist": 2048}
}

13.2 准确性风险 ​

风险4: 章节识别错误 ​

风险描述: 某些文档的章节层级识别不准确

影响: 分块质量下降,检索准确率降低

概率: 中 (15-25%)

应对措施:

  1. 人工审核和修正
java
@RestController
@RequestMapping("/api/v1/document-tree")
public class DocumentTreeReviewController {

    /**
     * 获取文档树(用于人工审核)
     */
    @GetMapping("/{documentId}")
    public R<DocumentTreeDTO> getDocumentTree(@PathVariable Long documentId) {
        DocumentTree tree = docNodeService.getTreeByDocumentId(documentId);
        return R.ok(DocumentTreeDTO.from(tree));
    }

    /**
     * 修正节点类型
     */
    @PutMapping("/node/{nodeId}/type")
    public R<Void> updateNodeType(
            @PathVariable Long nodeId,
            @RequestParam NodeType newType) {

        DocumentNode node = docNodeService.findById(nodeId);
        node.setType(newType);
        docNodeService.updateById(node);

        // 重新向量化受影响的chunks
        reVectorizeAffectedChunks(nodeId);

        return R.ok();
    }
}
  1. 质量评分
java
public class DocumentTreeQualityScorer {

    /**
     * 评估文档树质量
     */
    public double scoreQuality(DocumentTree tree) {
        double score = 0.0;

        // 指标1: 章节层级深度合理性
        int maxDepth = tree.getMaxDepth();
        if (maxDepth >= 2 && maxDepth <= 5) {
            score += 0.3;
        }

        // 指标2: 章节数量合理性
        int chapterCount = tree.getChapterCount();
        int totalPages = tree.getMetadata().getTotalPages();
        double chaptersPerPage = (double) chapterCount / totalPages;
        if (chaptersPerPage >= 0.02 && chaptersPerPage <= 0.2) {  // 平均5-50页一章
            score += 0.3;
        }

        // 指标3: 节点类型分布合理性
        Map<NodeType, Long> typeDistribution = tree.getTypeDistribution();
        if (typeDistribution.get(NodeType.PARAGRAPH) > chapterCount) {
            score += 0.2;  // 段落应该多于章节
        }

        // 指标4: 置信度
        double avgConfidence = tree.getAverageConfidence();
        score += 0.2 * avgConfidence;

        return score;
    }
}

风险5: 检索准确率未达预期 ​

风险描述: 新系统的检索准确率可能不如预期

影响: 用户满意度下降

概率: 中 (20-30%)

应对措施:

  1. A/B测试对比
java
@Service
public class ABTestRetrievalService {

    /**
     * A/B测试:同时执行新旧检索,对比结果
     */
    public ABTestResult abTest(Query query) {
        // A组:简单检索
        SimpleRetrievalResult resultA = simpleService.retrieve(
            query.getDatasetId(),
            query.getText()
        );

        // B组:结构化检索
        RetrievalResult resultB = structuredService.retrieve(
            query,
            RetrievalConfig.getDefault()
        );

        // 记录对比数据
        recordABTestMetrics(query, resultA, resultB);

        // 默认返回B组结果,但记录A组用于对比
        return ABTestResult.builder()
            .query(query)
            .resultA(resultA)
            .resultB(resultB)
            .build();
    }
}
  1. 准确率评测
java
@Service
public class AccuracyEvaluationService {

    /**
     * 批量评测准确率
     */
    public EvaluationReport evaluate(List<TestCase> testCases) {
        int correctCount = 0;

        for (TestCase testCase : testCases) {
            // 执行检索
            RetrievalResult result = retrievalService.retrieve(
                testCase.getQuery(),
                RetrievalConfig.getDefault()
            );

            // 检查是否包含预期答案
            boolean correct = result.getResults().stream()
                .anyMatch(r -> testCase.getExpectedDocumentIds()
                    .contains(r.getOriginalResult().getDocumentId()));

            if (correct) {
                correctCount++;
            }
        }

        double accuracy = (double) correctCount / testCases.size();

        return EvaluationReport.builder()
            .totalCases(testCases.size())
            .correctCount(correctCount)
            .accuracy(accuracy)
            .build();
    }
}

13.3 业务风险 ​

风险6: 用户学习成本 ​

风险描述: 新功能可能需要用户学习和适应

影响: 用户接受度低

概率: 低 (< 10%)

应对措施:

  • 提供详细的使用文档和教程
  • 新旧功能并行,渐进式切换
  • 收集用户反馈,持续优化

风险7: 性能回退 ​

风险描述: 新系统在某些场景下性能可能不如旧系统

影响: 用户体验下降

概率: 低 (< 10%)

应对措施:

  • 性能基准测试(Benchmark)
  • 灰度发布,监控性能指标
  • 提供降级开关

13.4 风险矩阵总结 ​

风险概率影响优先级应对措施
MinerU解析失败中中高✅ 后备解析器
大文档OOM低高中✅ 分片处理
Milvus性能瓶颈中高高✅ 分区+监控
章节识别错误中中中✅ 人工修正
检索准确率未达预期中高高✅ A/B测试
用户学习成本低低低✅ 文档+培训
性能回退低中中✅ 基准测试

14. 总结 ​

14.1 核心价值 ​

本设计方案通过引入结构化RAG系统,解决了传统固定大小分块的核心痛点:

✅ 问题1: 语义完整性 ​

传统方案: 固定512 tokens切分,章节被切断,列表被分散 新方案: 基于文档结构智能分块,保持章节、段落、列表的完整性

✅ 问题2: 上下文丢失 ​

传统方案: 检索到的chunk缺少层级上下文 新方案: 多级向量化 + 上下文补全,返回完整的章节上下文

✅ 问题3: 检索质量不稳定 ​

传统方案: 单一向量检索,难以应对多样化查询 新方案: 多路检索 + 重排序 + 结构化过滤,显著提升准确率


14.2 技术亮点 ​

  1. MinerU文档解析: 完整保留PDF/Word文档的层级结构
  2. 智能分块策略: 章节级、段落级、混合三种策略,灵活适配
  3. 多级向量化: 文档级、章节级、Chunk级三层向量,提升检索召回率
  4. 多路并行检索: 同时执行多种检索路径,结果融合后重排序
  5. 上下文补全: 自动补充父章节、相邻chunk、引用信息
  6. 向后兼容: 新旧系统共存,配置化切换,渐进式迁移

14.3 性能提升预期 ​

指标当前目标提升
检索准确率75%85%++10%
检索延迟(P95)1200ms420ms-65%
用户满意度3.5/54.2/5+20%
chunk质量60%90%++50%

14.4 实施建议 ​

优先级排序 ​

P0 - 必须实现 (Phase 1-3):

  • ✅ 数据模型设计和建表
  • ✅ MinerU集成和文档解析
  • ✅ 智能分块策略
  • ✅ 多级向量化

P1 - 重要功能 (Phase 4):

  • ✅ 多路检索
  • ✅ 重排序和上下文补全
  • ✅ Citation生成

P2 - 可选优化 (Phase 5):

  • ✅ 向后兼容和迁移工具
  • ⭕ 性能优化(按需)
  • ⭕ 高级功能(图片向量化、多模态等)

分阶段上线 ​

第一阶段 (Week 1-9): 核心功能开发
├─ Phase 1: 基础设施
├─ Phase 2: 智能分块
└─ Phase 3: 多级向量化

第二阶段 (Week 10-13): 检索功能
└─ Phase 4: 结构化检索

第三阶段 (Week 14-15): 迁移上线
├─ Phase 5: 向后兼容
└─ 灰度发布

第四阶段 (Week 16+): 优化迭代
├─ 性能优化
├─ 准确率调优
└─ 新功能扩展

14.5 成功标准 ​

技术指标 ​

  • [ ] 文档解析成功率 > 98%
  • [ ] 章节识别准确率 > 95%
  • [ ] 检索准确率 > 85%
  • [ ] 检索延迟(P95) < 500ms
  • [ ] 单元测试覆盖率 > 80%

业务指标 ​

  • [ ] 用户满意度 > 4.0/5.0
  • [ ] 灰度发布无P0故障
  • [ ] 数据迁移无丢失
  • [ ] 新系统准确率 > 旧系统

文档指标 ​

  • [ ] 技术文档齐全
  • [ ] 用户指南完整
  • [ ] API文档更新
  • [ ] 团队培训完成

14.6 下一步行动 ​

  1. 立即开始 (本周):

    • [ ] 评审本设计方案,收集反馈
    • [ ] 确定项目优先级和时间线
    • [ ] 组建开发团队(2-3人)
    • [ ] 准备开发环境(MinerU部署、Milvus配置)
  2. Week 1-2:

    • [ ] 创建数据库表
    • [ ] 搭建Milvus Collection
    • [ ] 实现核心数据结构
    • [ ] 编写单元测试框架
  3. Week 3-4:

    • [ ] 集成MinerU
    • [ ] 实现DocumentParser
    • [ ] 构建DocumentTree
    • [ ] 测试解析质量

14.7 参考资源 ​

技术文档 ​

相关论文 ​

  • "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks" (RAG原理)
  • "Dense Passage Retrieval for Open-Domain Question Answering" (检索原理)
  • "Learning to Retrieve: How to Train a Dense Retrieval Model Effectively" (检索优化)

附录 ​

A. 数据库完整Schema ​

详见章节 6.1

B. API接口定义 ​

java
// 向量化API
POST /api/v1/vectorization/document/{documentId}
POST /api/v1/vectorization/dataset/{datasetId}
GET  /api/v1/vectorization/task/{taskId}

// 检索API
POST /api/v1/retrieval/search
POST /api/v1/retrieval/structured-search

// 管理API
POST /api/v1/admin/dataset/{datasetId}/switch-strategy
POST /api/v1/admin/dataset/{datasetId}/migrate
GET  /api/v1/admin/metrics/vectorization
GET  /api/v1/admin/metrics/retrieval

C. 配置示例 ​

yaml
# application-structured-rag.yml
structured-rag:
  # 文档解析配置
  document-parser:
    provider: mineru  # mineru | tika
    mineru:
      api-url: http://localhost:8000
      timeout: 300000  # 5分钟

  # 分块配置
  chunking:
    strategy: hybrid  # section | paragraph | hybrid
    max-chunk-size: 2000
    min-chunk-size: 50
    overlap-size: 200

  # 向量化配置
  vectorization:
    enable-document-level: true
    enable-chapter-level: true
    enable-chunk-level: true
    batch-size: 100

  # 检索配置
  retrieval:
    multi-path-enabled: true
    reranking-enabled: true
    context-enrichment-enabled: true
    top-k: 10

D. 监控指标 ​

java
// 关键监控指标
metrics.counter("vectorization.documents.total");
metrics.counter("vectorization.documents.success");
metrics.counter("vectorization.documents.failed");

metrics.timer("vectorization.duration");
metrics.timer("parsing.duration");
metrics.timer("chunking.duration");

metrics.timer("retrieval.duration");
metrics.gauge("retrieval.accuracy");
metrics.counter("retrieval.requests.total");

metrics.gauge("milvus.vectors.count");
metrics.gauge("milvus.index.size.mb");

文档版本: v1.0 最后更新: 2025-12-15 作者: AI Architecture Team 状态: ✅ 设计完成,待评审