RAG 分块术完全指南:15种“切片神技”,让你的检索结果提升10倍!附实战代码
为什么你精心构建的 RAG 系统,返回的答案却总是“不着调”?不是模型不够强,而是你没“切”对!
RAG(检索增强生成)系统的精髓,不在于你用了哪个 embedding 模型,也不在于你接入了哪个 LLM,而在于——你如何「切」文本。切得好,信息上下文完整、检索精准;切不好,模型不是“胡说八道”,就是“词不达意”。
今天就来带你一次性掌握 15种最实用的 RAG 分块技巧,每种方法都配有真实场景和分块示例,甚至直接可用的代码结构。建议收藏 + 实战验证!
1. 按行切分(Line-by-Line Chunking)
适用场景: 聊天记录、逐行转录、问答型文本
推荐理由: 每行是一段完整语义,便于精确检索。
def line_chunk(text): return [line.strip() for line in text.strip().split('\n') if line.strip()]
输入示例:
Alice: Hey Bob, are you free for a call at 3 PM today?Bob: Sure, Alice. Do you want to discuss the project updates?Alice: Yes, and we need to talk about the client meeting.Bob: Sounds good! See you at 3.
分块结果:
CHUNK1: Alice: Hey Bob, are you free for a call at 3 PM today?CHUNK2: Bob: Sure, Alice. Do you want to discuss the project updates?CHUNK3: Alice: Yes, and we need to talk about the client meeting.CHUNK4: Bob: Sounds good! See you at 3.
⚠️注意: 如果每行太短,容易导致模型缺乏上下文,出现幻觉。
2. 固定大小切分(Fixed-Size Chunking)
适用场景: 无结构、无标点文本如OCR、爬虫原始内容
推荐理由: 保证块均匀,便于存储和处理
def fixed_chunk(text, size=20): words = text.split() return [' '.join(words[i:i+size]) for i in range(0, len(words), size)]
输入文本:
Python is a high-level, interpreted programming language...
代码实现:
import textwrapdef fixed_chunk(text, size=20): words = text.split() chunks = [' '.join(words[i:i+size]) for i in range(0, len(words), size)] return chunks
输出(每20词一块):
CHUNK1: Python is a high-level, interpreted programming language...CHUNK2: ...paradigms, including structured, object-oriented, and functional...
3. 滑动窗口切分(Sliding Window Chunking)
适用场景: 句意跨行的文本,如技术文档、合同
推荐理由: 保留上下文,防止语义断裂
Python 示例:
def sliding_window_chunk(text, size=15, overlap=5): words = text.split() chunks = [] for i in range(0, len(words) - size + 1, size - overlap): chunk = ' '.join(words[i:i + size]) chunks.append(chunk) return chunks
4. 按句子切分(Sentence-Based Chunking)
适用场景: 清洗过的文章、教材、技术博客
推荐理由: 每句是独立语义,利于拼接重组
import nltknltk.download('punkt')from nltk.tokenize import sent_tokenize
def sentence_chunk(text): return sent_tokenize(text)
示例输入:
Deep learning has transformed many fields of technology. Neural networks...
输出:
CHUNK1: Deep learning has transformed many fields of technology.CHUNK2: Neural networks can now outperform humans in image recognition.
5. 按段落切分(Paragraph Chunking)
适用场景: 博客、论文、演讲稿
推荐理由: 段落天然是完整语义单元
def paragraph_chunk(text): return [p.strip() for p in text.strip().split('\n\n') if p.strip()]
代码逻辑:
def paragraph_chunk(text): return text.strip().split('\n\n') # 假设段落间有空行
6. 按页切分(Page-Based Chunking)
适用场景: PDF、扫描文档、合同
推荐理由: 页码在文档中具有检索价值(如法院文件)
def page_chunk(text): return [page.strip() for page in text.strip().split('\f') if page.strip()] # 使用 \f 分页符
7. 按标题或小节切分(Section or Heading Chunking)
适用场景: Markdown 文档、说明书、白皮书
import re
def section_chunk(text): chunks = [] sections = re.split(r'(?m)^#+\s+', text) headings = re.findall(r'(?m)^#+\s+(.*)', text) for i, section in enumerate(sections[1:]): chunks.append(f"# {headings[i]}\n{section.strip()}") return chunks
示例输入:
# IntroductionRAG allows LLMs to use external knowledge.# How RAG WorksRAG retrieves context and then generates.
输出:
CHUNK1: # Introduction \n RAG allows LLMs to use external knowledge.CHUNK2: # How RAG Works \n RAG retrieves context and then generates.
8. 关键词切分(Keyword-Based Chunking)
适用场景: 医疗记录、操作手册、FAQ
逻辑: 遇到关键词(如“Note:”、“Step”)即切断
def keyword_chunk(text, keywords=["Note:", "Step", "Q:", "A:"]): import re pattern = '|'.join([re.escape(k) for k in keywords]) parts = re.split(f'(?=\\b({pattern}))', text) return [''.join(parts[i:i+2]).strip() for i in range(0, len(parts), 2)]
9. 实体切分(Entity-Based Chunking)
适用场景: 新闻、评论、法律文书
方法: 使用 NER 工具提取实体,按实体聚合内容
Python 示例(用 spaCy):
import spacynlp = spacy.load("en_core_web_sm")doc = nlp(text)for ent in doc.ents: print(ent.text, ent.label_)
10. Token切分(Token-Based Chunking)
适用场景: 控制 LLM 输入大小,防止上下文超长
工具: 使用 tiktoken
计算 Token 数量
import tiktoken
def token_chunk(text, max_tokens=200, model="gpt-3.5-turbo"): enc = tiktoken.encoding_for_model(model) tokens = enc.encode(text) chunks = [tokens[i:i+max_tokens] for i in range(0, len(tokens), max_tokens)] return [enc.decode(chunk) for chunk in chunks]
11. 表格切分(Table Chunking)
适用场景: 财报、研究论文、发票
方法: 整张表作为一块,或者逐行切分,结合周围文字
def table_chunk(text): tables = [] blocks = text.split('\n\n') for block in blocks: lines = block.strip().split('\n') if all('|' in line for line in lines): # 简单判断为表格 tables.append(block) return tables
12. 递归切分(Recursive Chunking)
适用场景: 内容结构不均的文本(长段落 + 短句混合)
策略: 先大后小,从段落 → 句子 → 词语,直到符合 chunk 限制
def recursive_chunk(text, max_words=100): if len(text.split()) <= max_words: return [text] paragraphs = text.split('\n\n') chunks = [] for p in paragraphs: if len(p.split()) > max_words: sentences = sent_tokenize(p) current = [] for s in sentences: current.append(s) if len(' '.join(current).split()) >= max_words: chunks.append(' '.join(current)) current = [] if current: chunks.append(' '.join(current)) else: chunks.append(p) return chunks
13. 语义切分(Semantic Chunking)
适用场景: FAQ、客服日志、知识库
方法: 利用 embedding 聚类,按语义相近分组
from sklearn.cluster import KMeansfrom sentence_transformers import SentenceTransformer
def semantic_chunk(text, n_clusters=5): model = SentenceTransformer('all-MiniLM-L6-v2') sentences = sent_tokenize(text) embeddings = model.encode(sentences) kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(embeddings) clusters = [[] for _ in range(n_clusters)] for i, label in enumerate(kmeans.labels_): clusters[label].append(sentences[i]) return [' '.join(cluster) for cluster in clusters]
14. 层级切分(Hierarchical Chunking)
适用场景: 教材、法规、文档规范
方法: 按“章节 → 小节 → 段落”三层结构分割
def hierarchical_chunk(text): # 简单模拟:标题 => 小节 => 段落 levels = re.split(r'(#+\s.*)', text) result = [] for i in range(1, len(levels), 2): section = levels[i].strip() + '\n' + levels[i+1].strip() result.append(section) return result
15. 内容类型感知切分(Content-Type Aware Chunking)
适用场景: 图文混合PDF、科研报告、年报
策略: 图、表、正文、列表各自为块,避免混淆格式
def content_type_chunk(text): chunks = [] lines = text.splitlines() buffer = [] current_type = None
def flush(): if buffer: chunks.append('\n'.join(buffer)) buffer.clear()
for line in lines: if re.match(r'^\s*\|.*\|\s*$', line): if current_type != 'table': flush() current_type = 'table' elif re.match(r'^#+\s+', line): if current_type != 'heading': flush() current_type = 'heading' elif re.match(r'^[-*]\s+', line): if current_type != 'list': flush() current_type = 'list' else: if current_type != 'text': flush() current_type = 'text' buffer.append(line) flush() return chunks
📌总结:一张图快速回顾 15 种分块方式
编号 | 分块方式 | 最适用场景 | 是否语义保持 | 实现难度 |
---|---|---|---|---|
1 | 按行切分 | 聊天记录、逐行转录 | ✅ | 🟢低 |
2 | 固定词数 | OCR、爬虫数据 | ❌ | 🟢低 |
3 | 滑动窗口 | 技术文档、连贯句 | ✅✅ | 🟡中 |
4 | 按句子 | 教材、博客 | ✅ | 🟢低 |
5 | 按段落 | 正式文章 | ✅✅ | 🟢低 |
6 | 按页 | PDF、法律合同 | ✅ | 🟢低 |
7 | 按标题/小节 | 文档、白皮书 | ✅✅ | 🟢低 |
8 | 关键词触发 | 表单、医疗记录 | ✅ | 🟡中 |
9 | 实体识别分组 | 新闻、评论 | ✅✅ | 🟡中 |
10 | Token限制 | 所有LLM处理 | ✅ | 🟡中 |
11 | 表格单独分块 | 财报、学术报告 | ✅✅ | 🟡中 |
12 | 递归切分 | 结构混乱文档 | ✅✅ | 🔴高 |
13 | 语义聚类 | FAQ、知识库 | ✅✅✅ | 🔴高 |
14 | 多层级结构切分 | 教材、技术文档 | ✅✅✅ | 🔴高 |
15 | 内容类型感知 | 图文混合PDF | ✅✅ | 🔴高 |
结语:选对“切法”,LLM 才能答对问题
构建 RAG 系统时,最容易被忽略、却最影响效果的关键环节,往往是「Chunking」。
别再盲目用默认的 chunk 大小了。回顾你的数据结构,选择合适的分块策略,才能让 RAG 如虎添翼,检索又准又稳!
零基础入门AI大模型
今天贴心为大家准备好了一系列AI大模型资源,包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。
有需要的小伙伴,可以点击下方链接免费领取【保证100%免费
】
1.学习路线图
第一阶段: 从大模型系统设计入手,讲解大模型的主要方法;
第二阶段: 在通过大模型提示词工程从Prompts角度入手更好发挥模型的作用;
第三阶段: 大模型平台应用开发借助阿里云PAI平台构建电商领域虚拟试衣系统;
第四阶段: 大模型知识库应用开发以LangChain框架为例,构建物流行业咨询智能问答系统;
第五阶段: 大模型微调开发借助以大健康、新零售、新媒体领域构建适合当前领域大模型;
第六阶段: 以SD多模态大模型为主,搭建了文生图小程序案例;
第七阶段: 以大模型平台应用与开发为主,通过星火大模型,文心大模型等成熟大模型构建大模型行业应用。
2.视频教程
网上虽然也有很多的学习资源,但基本上都残缺不全的,这是我自己整理的大模型视频教程,上面路线图的每一个知识点,我都有配套的视频讲解。
(都打包成一块的了,不能一一展开,总共300多集)
3.技术文档和电子书
这里主要整理了大模型相关PDF书籍、行业报告、文档,有几百本,都是目前行业最新的。
4.LLM面试题和面经合集
这里主要整理了行业目前最新的大模型面试题和各种大厂offer面经合集。
👉学会后的收获:👈
• 基于大模型全栈工程实现(前端、后端、产品经理、设计、数据分析等),通过这门课可获得不同能力;
• 能够利用大模型解决相关实际项目需求: 大数据时代,越来越多的企业和机构需要处理海量数据,利用大模型技术可以更好地处理这些数据,提高数据分析和决策的准确性。因此,掌握大模型应用开发技能,可以让程序员更好地应对实际项目需求;
• 基于大模型和企业数据AI应用开发,实现大模型理论、掌握GPU算力、硬件、LangChain开发框架和项目实战技能, 学会Fine-tuning垂直训练大模型(数据准备、数据蒸馏、大模型部署)一站式掌握;
• 能够完成时下热门大模型垂直领域模型训练能力,提高程序员的编码能力: 大模型应用开发需要掌握机器学习算法、深度学习框架等技术,这些技术的掌握可以提高程序员的编码能力和分析能力,让程序员更加熟练地编写高质量的代码。
1.AI大模型学习路线图
2.100套AI大模型商业化落地方案
3.100集大模型视频教程
4.200本大模型PDF书籍
5.LLM面试题合集
6.AI产品经理资源合集
5.免费获取
这份完整版的大模型 AI 学习资料已经上传优快云,朋友们如果需要可以微信扫描下方优快云官方认证二维码或者点击以下链接都可以免费领取【保证100%免费】