https://docs.llamaindex.ai/en/stable/module_guides/indexing/lpg_index_guide/#dynamicllmpathextractor
使用LlamaIndex中的PropertyGraphIndex:深入探索与实战指南
在现代数据处理和知识管理中,属性图(Property Graph)是一种强大的工具,用于表示复杂的实体关系和元数据。LlamaIndex 提供了一个名为 PropertyGraphIndex 的工具,帮助我们构建和查询这些属性图。本文将深入探讨如何在 LlamaIndex 中使用 PropertyGraphIndex,并通过详细的代码示例和解释,帮助你快速上手和应用。
前置知识
在深入学习 PropertyGraphIndex 之前,你需要了解以下基础知识:
- 属性图(Property Graph):属性图是一种图数据结构,其中节点(Node)和边(Edge)都可以带有属性(Property)。节点通常表示实体,边表示实体之间的关系。
- LlamaIndex:LlamaIndex 是一个用于构建和查询知识图谱的工具库。它提供了多种索引类型,包括
PropertyGraphIndex。 - Python 基础:熟悉 Python 编程语言,包括类、方法、模块导入等基本概念。
基本使用
导入并创建 PropertyGraphIndex
首先,我们需要导入 PropertyGraphIndex 类,并使用文档创建一个索引。
from llama_index.core import PropertyGraphIndex
# 创建索引
index = PropertyGraphIndex.from_documents(
documents,
)
使用索引进行查询
创建索引后,我们可以使用它来检索节点和执行查询。
# 创建检索器
retriever = index.as_retriever(
include_text=True, # 包含匹配路径的源块
similarity_top_k=2, # 向量知识图谱节点检索的前 k 个
)
# 检索节点
nodes = retriever.retrieve("Test")
# 创建查询引擎
query_engine = index.as_query_engine(
include_text=True, # 包含匹配路径的源块
similarity_top_k=2, # 向量知识图谱节点检索的前 k 个
)
# 执行查询
response = query_engine.query("Test")
保存和加载索引
我们可以将索引保存到磁盘,并在需要时加载它。
# 保存索引
index.storage_context.persist(persist_dir="./storage")
# 加载索引
from llama_index.core import StorageContext, load_index_from_storage
storage_context = StorageContext.from_defaults(persist_dir="./storage")
index = load_index_from_storage(storage_context)
从现有图存储加载索引
如果你已经有了一个图存储(Graph Store)和可选的向量存储(Vector Store),可以直接从这些存储中加载索引。
# 从现有图存储和向量存储加载索引
index = PropertyGraphIndex.from_existing(
property_graph_store=graph_store,
vector_store=vector_store,
...
)
构建属性图
在 LlamaIndex 中,属性图的构建是通过对每个块(Chunk)执行一系列的 kg_extractors,并将实体和关系作为元数据附加到每个 LlamaIndex 节点上。你可以使用多个 kg_extractors,它们都会被应用。
index = PropertyGraphIndex.from_documents(
documents,
kg_extractors=[extractor1, extractor2, ...],
)
# 插入额外的文档或节点
index.insert(document)
index.insert_nodes(nodes)
如果没有提供 kg_extractors,默认使用 SimpleLLMPathExtractor 和 ImplicitPathExtractor。
SimpleLLMPathExtractor
SimpleLLMPathExtractor 使用 LLM 提取短语句,并解析单跳路径(single-hop paths),格式为 (entity1, relation, entity2)。
from llama_index.core.indices.property_graph import SimpleLLMPathExtractor
kg_extractor = SimpleLLMPathExtractor(
llm=llm,
max_paths_per_chunk=10,
num_workers=4,
show_progress=False,
)
你还可以自定义提示和解析路径的函数。
prompt = (
"Some text is provided below. Given the text, extract up to "
"{max_paths_per_chunk} "
"knowledge triples in the form of `subject,predicate,object` on each line. Avoid stopwords.\n"
)
def parse_fn(response_str: str) -> List[Tuple[str, str, str]]:
lines = response_str.split("\n")
triples = [line.split(",") for line in lines]
return triples
kg_extractor =</

最低0.47元/天 解锁文章
1433

被折叠的 条评论
为什么被折叠?



