LlamaIndex 四 Documents与Nodes

欢迎来到我的LlamaIndex系列,如果您也和我一样,在搭建RAG应用时,了解到了LlamaIndex, 那就请一起来学习它的各个功能模块和demo实例。

LlamaIndex 一 简单文档查询 - 掘金 (juejin.cn)

LlamIndex二 RAG应用开发 - 掘金 (juejin.cn)

LlamaIndex三 配置 - 掘金 (juejin.cn)

LlamaIndex 四 数据连接器 - 掘金 (juejin.cn)

LlamaIndex在开发RAG应用过程中,一路电光带火石,上篇应对不同格式数据的各种数据连接器,仿佛十八般兵器,让我们应接不暇。本篇,我们就继连接器之后,来到LlamaIndex处理各式数据的核心概念,Document和Nodes,它是索引前的重要步骤。

前言

RAG应用开发,就像摆酒。要处理各式数据,犹如乾隆老爷子当年摆下的千叟宴。数据连接器把吃席的请进来了,接下来怎么张罗呢?在LlamaIndex中,提供了DocumentNode两个数据抽象概念。

Document

Document是各式数据源的容器:数据连接器把数据加载后,得到的是一个抽象的Document对象。不管是PDF,还是API响应,或是数据库等,皆是由一个Document对象来托管。

  • Document内容

Document包含文本数据和在头部包含一些文件的属性,如元数据、关系数据。让我们来看个例子。

ini 复制代码
from llama_index import Document
text_list = ["hello", "world"]
documents = [Document(text=t) for t in text_list]

首先,我们从llama_index中引入Document,接着申明了一个数组,每一项为文本,最后,我们设置了Document的text属性,返回了一个documents数组。

  • 自定义Document

上面的例子我们通过Document的text定制了内容,接下来我们来定义元数据。

javascript 复制代码
from llama_index import Document
document = Document(
    text='Hello World',
    metadata={
        'filename': 'hello_world.pdf',
        'category': 'science'
    }
)

在设置内容为text的同时,我们还在创建这个文档时指定元数据中文件名为hello_world.pdf,分类为science

我们也可以修改document对象的meta属性,这里做了重命名。

ini 复制代码
document.metadata = {'filename': 'hello_world_v2.pdf'}

我们也可以设置文档id

ini 复制代码
from llama_index import Document
document = Document(text='Hello World')
document.doc_id = "xxxx-yyyy"
  • SimpleDirectoryReader中设置
ini 复制代码
from llama_index import SimpleDirectoryReader
filenama_hook = lambda filename: {'file_name': filename}
documents = SimpleDirectoryReader('./data', file_metadata=filenama_hook).load_data()

filename_hook 返回的是一个lambda 的匿名函数(<function <lambda> at 0x000001F2829AE160>)。该函数接受一个filename的参数,并返回一个Dic。其中包含一个键值对:'filename':filename。

看上图打印结果,SimpleDirectoryReader的file_metadata参数,设置了在目录中每次加载文件时的回调。

Node

Document作为数据窗口,对数据分割解析,Node就是相应的抽象。Node是LlamaIndex中的一等公民,也包含了和Document一样的数据和属性。Document由Nodes构成。

python 复制代码
from llama_index.schema import TextNode
node = TextNode(text="hello world", id_="1234-5678")
print(node)
  • 从Document中拿到Nodes
ini 复制代码
from llama_index import Document
from llama_index.node_parser import SimpleNodeParser

text_list = ["hello", "world"]
documents = [Document(text=t) for t in text_list]

parser = SimpleNodeParser.from_defaults()
nodes = parser.get_nodes_from_documents(documents)

我们从llama_index的node_parser模块中引入了SimpleNodeParser, 接下来和之前的例子一样,循环字符串数组生成了两个Document,最后调用parser的get_nodes_from_document方法得到了文档的所有结点。

php 复制代码
[TextNode(id_='9d03ae8a-5b2d-4cc4-9c72-b25891050224', embedding=None, metadata={}, excluded_embed_metadata_keys=[], excluded_llm_metadata_keys=[], relationships={<NodeRelationship.SOURCE: '1'>: RelatedNodeInfo(node_id='c6896cee-18b0-45e2-927f-bc9b497dfe21', node_type=<ObjectType.DOCUMENT: '4'>, metadata={}, hash='7debe8d278fe6c55c45f979269ab268102d75f8d48644d244cd0050dae0846ac'), <NodeRelationship.NEXT: '3'>: RelatedNodeInfo(node_id='16da9220-0f7e-4713-b923-1a426ea9064e', node_type=<ObjectType.TEXT: '1'>, metadata={}, hash='12d52a924ac6bc76ec4101c5d1f55bb5b5365d5f4c524a21d6175a4b049a1962')}, hash='7debe8d278fe6c55c45f979269ab268102d75f8d48644d244cd0050dae0846ac', text='hello', start_char_idx=0, end_char_idx=5, text_template='{metadata_str}\n\n{content}', metadata_template='{key}: {value}', metadata_seperator='\n')...]

大家可以通过打印看到Node和Document类似,有text和metadata等属性。

  • 自定义Node

我们还可以像前端node结点一样来拼装nodes 到Document

ini 复制代码
from llama_index.schema import TextNode, NodeRelationship, RelatedNodeInfo

hello_node = TextNode(text="Hello", id_="1111-1111")
world_node = TextNode(text="World", id_="2222-2222")

hello_node.relationships[NodeRelationship.NEXT] = RelatedNodeInfo(node_id=world_node.node_id, metadata={"created_by": "VerySmallWoods"})
world_node.relationships[NodeRelationship.PREVIOUS] = RelatedNodeInfo(node_id=hello_node.node_id)
nodes = [hello_node, world_node]

有这么细的手工活,我们可以慢慢组装结点了。这对之后的一些高级活是很重要的。

总结

  • LlamaIndex这只"八爪鱼"在连接完各式各样的数据后,使用DocumentNode的抽象概念,进一步处理数据。
  • 通过LlamaInex提供的Document和Node对象,我们可以对数据文件进行一些业务相关的处理。

参考资料

相关推荐
yuhulkjv33519 小时前
豆包导出的Excel公式失效
人工智能·ai·chatgpt·excel·豆包·deepseek·ai导出鸭
2501_920953861 天前
工业4.0时代,制造企业精益管理咨询的标准化实施步骤
大数据·人工智能·制造
~央千澈~1 天前
《2026鸿蒙NEXT纯血开发与AI辅助》第四章 对鸿蒙next项目结构目录详解以及实战解决一个最初的依赖安装的报错·卓伊凡
人工智能
xinlianyq1 天前
2026企业流量破局:四大主流短视频矩阵获客系统深度解析与选型指南
人工智能·矩阵
workflower1 天前
用硬件换时间”与“用算法降成本”之间的博弈
人工智能·算法·安全·集成测试·无人机·ai编程
Cx330❀1 天前
一文吃透Linux System V共享内存:原理+实操+避坑指南
大数据·linux·运维·服务器·人工智能
OPHKVPS1 天前
Anthropic 为 Claude Code 推出“自动模式”:AI 编码工具迈向更高自主性
网络·人工智能·安全·ai
Allen_LVyingbo1 天前
斯坦福HAI官网完整版《2025 AI Index Report》全面解读
人工智能·数学建模·开源·云计算·知识图谱
金融小师妹1 天前
基于AI通胀预期建模与能源冲击传导机制的政策分析:高频信号下的风险再评估
人工智能·svn·能源