31 使用属性图索引:构建和查询知识图谱

使用属性图索引:构建和查询知识图谱

在LlamaIndex中,属性图索引(PropertyGraphIndex)是一种强大的工具,用于构建和查询知识图谱。属性图是一种知识集合,由带标签的节点(如实体类别、文本标签等)和属性(如元数据)组成,通过关系链接成结构化的路径。

使用方法

基本用法

你可以通过导入类并使用它来实现基本用法:

from llama_index.core import PropertyGraphIndex

# 创建索引
index = PropertyGraphIndex.from_documents(
    documents,
)

# 使用索引
retriever = index.as_retriever(
    include_text=True,  # 包含匹配路径的源块
    similarity_top_k=2,  # 向量知识图节点检索的top k
)
nodes = retriever.retrieve("Test")

query_engine = index.as_query_engine(
    include_text=True,  # 包含匹配路径的源块
    similarity_top_k=2,  # 向量知识图节点检索的top k
)
response = query_engine.query("Test")

# 保存和加载
index.storage_context.persist(persist_dir="./storage")

from llama_index.core import StorageContext, load_index_from_storage

index = load_index_from_storage(
    StorageContext.from_defaults(persist_dir="./storage")
)

# 从现有的图存储(和可选的向量存储)加载
index = PropertyGraphIndex.from_existing(
    property_graph_store=graph_store, vector_store=vector_store, ...
)

构建属性图

在LlamaIndex中,属性图的构建通过一系列的kg_extractors对每个块进行处理,并将实体和关系作为元数据附加到每个llama-index节点上。你可以使用多个kg_extractors,它们都会被应用。

如果没有提供,默认使用SimpleLLMPathExtractor和ImplicitPathExtractor。

index = PropertyGraphIndex.from_documents(
    documents,
    kg_extractors=[extractor1, extractor2, ...],
)

# 插入额外的文档/节点
index.insert(document)
index.insert_nodes(nodes)

kg_extractors详解

(默认) SimpleLLMPathExtractor

使用LLM提取短语句,提示并解析单跳路径,格式为(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,
)
(默认) ImplicitPathExtractor

使用每个llama-index节点对象的node.relationships属性提取路径:

from llama_index.core.indices.property_graph import ImplicitPathExtractor

kg_extractor = ImplicitPathExtractor()
DynamicLLMPathExtractor

根据可选的允许实体类型和关系类型列表提取路径(包括实体类型!)。如果没有提供,LLM将根据需要分配类型。如果提供了,它将帮助引导LLM,但不会强制执行这些类型:

from llama_index.core.indices.property_graph import DynamicLLMPathExtractor

kg_extractor = DynamicLLMPathExtractor(
    llm=llm,
    max_triplets_per_chunk=20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

需要重新演唱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值