59-LlamaIndex入门-数据索引框架-vs-LangChain对比
文章目录
【59.Python+AI】LlamaIndex入门:为什么做RAG的人最后都转向了它
📖 文章简介: 本文系统介绍LlamaIndex——一个在RAG场景下比LangChain更专注的数据框架。内容涵盖LlamaIndex的核心数据结构抽象(Node/Document)、索引类型对比(向量索引/摘要索引/树索引/知识图谱索引)、IngestionPipeline数据摄入管道的设计理念,以及与LangChain在RAG场景下的功能对比矩阵。配以Mermaid架构图展示LlamaIndex的索引体系,适合已经在用LangChain做RAG、想了解"另一个选择"的开发者。

🎬 个人主页: 源码骑士
❄ 专栏传送门: 《Android开发基础》《python基础课程》
⭐️热衷从源码视角拆解技术底层原理,将复杂架构讲得通俗易懂
🎬 源码骑士的简介:(同上)
导入语
你一直用LangChain做RAG。但最近总听人说"LlamaIndex在数据索引方面更专业"——它到底专业在哪?值得再学一个新框架吗?
答案很简单:LangChain是通用AI框架(Agent/Chain/Tool什么都能做),LlamaIndex是数据索引专用框架(只做一件事:让LLM高效连接数据)。 如果你80%的工作是RAG,LlamaIndex可能比LangChain更顺手。这篇文章给你一个清晰的对比,5分钟就能上手写第一个LlamaIndex应用。
1 ~> LlamaIndex索引体系
2 ~> 5分钟上手
# pip install llama-index llama-index-embeddings-openai
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
# 1. 加载文档(一个目录下的所有文件)
documents = SimpleDirectoryReader("./my_docs").load_data()
# 2. 构建索引(一行代码)
index = VectorStoreIndex.from_documents(documents)
# 3. 查询
query_engine = index.as_query_engine()
response = query_engine.query("年假政策是什么?")
print(response)
对比LangChain的同样功能: LangChain需要手动组合Loader→Splitter→Embeddings→VectorStore→Retriever→Chain,LlamaIndex两行搞定。
3 ~> LangChain vs LlamaIndex 对比矩阵
| LangChain | LlamaIndex | |
|---|---|---|
| 定位 | 通用AI应用框架 | 数据索引与检索框架 |
| RAG上手难度 | 中(需理解Chain/Tool等概念) | 低(2行代码开始用) |
| 索引类型 | 向量索引为主 | 向量+摘要+树+知识图谱 |
| 数据摄入 | DocumentLoader + Splitter组合 | IngestionPipeline统一管道 |
| Agent支持 | ⭐⭐⭐⭐⭐ 核心能力 | ⭐⭐ 有限 |
| 复杂工作流 | ⭐⭐⭐⭐⭐ LCEL + LangGraph | ⭐⭐ |
| 数据连接器 | ⭐⭐⭐⭐ 200+ | ⭐⭐⭐⭐ 160+ |
| 最佳场景 | Agent、复杂工作流 | 企业知识库、数据密集型RAG |
4 ~> LlamaIndex的独有特性
多种索引类型
# 除了向量索引,LlamaIndex还支持:
from llama_index.core import SummaryIndex, TreeIndex, KnowledgeGraphIndex
# 摘要索引:适合"这篇文章整体讲了什么"
summary_index = SummaryIndex.from_documents(docs)
# 树索引:适合多级分类的问答
tree_index = TreeIndex.from_documents(docs)
# 知识图谱索引:实体关系检索
kg_index = KnowledgeGraphIndex.from_documents(docs)
IngestionPipeline:声明式数据管道
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.extractors import TitleExtractor
pipeline = IngestionPipeline(
transformations=[
SentenceSplitter(chunk_size=500),
TitleExtractor(), # 自动提取标题
OpenAIEmbedding(),
]
)
nodes = pipeline.run(documents=documents)
思考 && 总结
- LlamaIndex是RAG专用工具: 如果你90%的工作是"文档→索引→问答",LlamaIndex的API比LangChain简洁得多。
- LangChain是通用框架: Agent、复杂工作流、多工具编排是它的优势;纯RAG场景用LlamaIndex更快。
- 两者可以混用: LlamaIndex建索引 + LangChain做Agent编排,是很多团队的实践。
- 索引类型是LlamaIndex的杀手锏: 树索引和知识图谱索引在特定场景(层级分类、实体关系)比纯向量检索效果好。
- 不要面向框架编程: 需求驱动选框架,而不是学完一个框架再给它找应用场景。
LangChain是瑞士军刀,LlamaIndex是手术刀。割盲肠(做RAG)的时候,手术刀更快。
结尾
各位小伙伴,本文完!源码骑士 👀 | ❤️ | ⭐ | 💬 | 🔄 一键四连!🗡️ 寄语:好工具让你专注"问什么",而不是"怎么查"。
往期回顾:【Python+AI】LangSmith调试 / 【Python+AI】LangChain Memory / 【Python+AI】LCEL流水线 / 【Python+AI】LangChain核心概念 / 【Python+AI】企业知识库
更多推荐


所有评论(0)