Document Ingestion
Document Ingestion 是从各种数据源(PDF、Word、网页、数据库)加载文档并转换为标准格式的过程。它是 RAG 管线的第一步。
#type / concept
#status / evergreen
#tech / ai
[!info] related notes
- 所属 MOC: RAG Engineering MOC
- 下游: Document Chunking
Document Ingestion
一句话定义
Document Ingestion 是从各种数据源加载文档并转换为标准格式的过程。PDF、Word、网页、数据库、API——各种格式的数据都需要统一成 Document 对象。
核心原理
数据源类型
| 数据源 | 加载方式 | 挑战 |
|---|---|---|
| PyPDF, pdfplumber | 表格、图片、多栏 | |
| Word | python-docx | 格式保留 |
| 网页 | BeautifulSoup, Trafilatura | 去噪、提取正文 |
| 数据库 | SQL 查询 | 结构化转文本 |
| API | HTTP 请求 | 认证、分页 |
| Markdown | 直接读取 | 格式解析 |
Document 对象
@dataclass
class Document:
content: str # 文本内容
metadata: dict # 元数据
source: str # 来源(文件路径、URL)
doc_type: str # 文档类型
Python 实现
class DocumentIngestionPipeline:
def __init__(self):
self.loaders = {
"pdf": PDFLoader(),
"docx": DocxLoader(),
"web": WebLoader(),
"markdown": MarkdownLoader(),
}
async def ingest(self, source: str, doc_type: str) -> list[Document]:
loader = self.loaders.get(doc_type)
if not loader:
raise ValueError(f"Unsupported doc type: {doc_type}")
documents = await loader.load(source)
return [self.normalize(doc) for doc in documents]
def normalize(self, doc: Document) -> Document:
# 清理文本
doc.content = self.clean_text(doc.content)
# 添加元数据
doc.metadata["ingested_at"] = datetime.now().isoformat()
return doc
常见坑
- 不做文本清理: PDF 提取的文本包含乱码、页眉页脚
- 不保留元数据: 丢失了来源、页码等信息
- 不做格式检测: PDF 是扫描件还是文本层 PDF