LlamaIndex 集成 Memgraph 图数据库:PropertyGraphStore 与 KnowledgeGraphStore 实战指南

LlamaIndex 集成 Memgraph 图数据库:PropertyGraphStore 与 KnowledgeGraphStore 实战指南 LlamaIndex 集成 Memgraph 图数据库PropertyGraphStore 与 KnowledgeGraphStore 实战指南【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_indexMemgraph 是一款面向实时数据流与快速分析场景的开源图数据库。在 LlamaIndex 中Memgraph 被集成作为图存储后端用于持久化知识图谱Knowledge Graph与属性图Property Graph两类索引数据并通过 Cypher 查询完成图检索。本文以仓库内 Memgraph 集成包 为对象系统讲解MemgraphPropertyGraphStore与MemgraphGraphStore的安装、连接、建索引与查询全流程并结合源码剖析其底层实现原理帮助你直接将 LlamaIndex 的图谱能力落到 Memgraph 上。集成包概览两类图存储两种索引形态Memgraph 集成包位于 llama-index-graph-stores-memgraph通过init.py 对外暴露两个类类名对应 LlamaIndex 索引数据模型适用场景MemgraphPropertyGraphStorePropertyGraphIndex属性图索引实体节点EntityNode 文本块节点ChunkNode 带属性关系现代属性图 RAG支持向量检索与结构化查询MemgraphGraphStoreKnowledgeGraphIndex知识图谱索引三元组subject-relation-object经典知识图谱构建与基于关系的问答从包配置 pyproject.toml 可见该包依赖llama-index-core0.13.0,0.15与neo4j5.24.0,6。Memgraph 与 Neo4j 共用 Bolt 协议与 Cypher 语言因此驱动层直接复用官方neo4jPython 驱动这是理解后续所有代码的前提。安装与环境准备安装集成包及其核心依赖pip install llama-index llama-index-graph-stores-memgraph运行前提本地已启动 Memgraph 实例默认 Bolt 端口为7687连接 URL 形如bolt://localhost:7687若使用默认用户名/密码username与password传空字符串即可两个 Store 的构造器都会在初始化时校验连接MemgraphGraphStore在连接失败时抛出ValueError详见源码 kg_base.py并在 Neo4j 驱动缺失时提示pip install neo4j。方案一MemgraphPropertyGraphStore 构建属性图 RAG属性图Property Graph是 LlamaIndex 推荐的现代图谱方案实体、文本块、关系都作为带属性的节点/边存储并且实体可以携带 embedding 向量从而同时支持向量相似度检索与结构化 Cypher 查询。完整示例从文档到属性图索引以下示例改编自集成包 README.md完整覆盖取数 → 连接 Memgraph → 抽取知识三元组 → 建索引 → 问答的链路import os import urllib.request import nest_asyncio from llama_index.core import SimpleDirectoryReader, PropertyGraphIndex from llama_index.graph_stores.memgraph import MemgraphPropertyGraphStore from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.openai import OpenAI from llama_index.core.indices.property_graph import SchemaLLMPathExtractor os.environ[OPENAI_API_KEY] YOUR_API_KEY # 替换为你的 OpenAI API Key os.makedirs(data/paul_graham/, exist_okTrue) url https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt output_path data/paul_graham/paul_graham_essay.txt urllib.request.urlretrieve(url, output_path) nest_asyncio.apply() # 预处理转义单引号避免后续 Cypher 参数化出现问题 with open(output_path, r, encodingutf-8) as file: content file.read() modified_content content.replace(, \\) with open(output_path, w, encodingutf-8) as file: file.write(modified_content) documents SimpleDirectoryReader(./data/paul_graham/).load_data() # 建立 Memgraph 连接请确保 Memgraph 已启动 username # Memgraph 用户名默认 password # Memgraph 密码默认 url # 连接地址例如 bolt://localhost:7687 graph_store MemgraphPropertyGraphStore( usernameusername, passwordpassword, urlurl, ) index PropertyGraphIndex.from_documents( documents, embed_modelOpenAIEmbedding(model_nametext-embedding-ada-002), kg_extractors[ SchemaLLMPathExtractor( llmOpenAI(modelgpt-3.5-turbo, temperature0.0), ) ], property_graph_storegraph_store, show_progressTrue, ) query_engine index.as_query_engine(include_textTrue) response query_engine.query(What happened at Interleaf and Viaweb?) print(\nDetailed Query Response:) print(str(response))构造参数与源码解读MemgraphPropertyGraphStore的构造器签名见 property_graph.py参数默认值说明username/password必填Memgraph 认证信息url必填Bolt 连接地址如bolt://localhost:7687databasememgraph目标数据库名refresh_schemaTrue初始化时是否立即刷新图谱 Schemasanitize_query_outputTrue是否对查询输出做清洗enhanced_schemaFalse是否启用增强 Schema 生成create_indexesTrue是否为__Node__/__Entity__标签创建id索引以加速导入与检索**neo4j_kwargs—透传给neo4j.GraphDatabase.driver的额外参数底层连接通过neo4j.GraphDatabase.driver(url, auth(username, password), **neo4j_kwargs)建立property_graph.py#L130-L132client属性直接暴露驱动句柄close()方法用于显式关闭连接# 显式关闭 Memgraph 连接 graph_store.close()数据写入upsert 节点与关系属性图写入由upsert_nodes与upsert_relations两个方法完成二者都采用UNWIND $data AS row批量参数化写入并以 1000 条为一批CHUNK_SIZE 1000分批提交文本块节点以MERGE (c:__Node__ {id: row.id})幂等写入设置text属性并打上Chunk标签存在 embedding 时写入c.embeddingproperty_graph.py#L330-L346实体节点同样以__Node__为基类标签 MERGE再追加__Entity__与业务标签SET e:row.label并建立 Chunk 到实体的MENTIONS关系property_graph.py#L348-L369关系CREATE (source)-[r:row.label]-(target)并SET r row.properties写入关系属性property_graph.py#L371-L390。数据读取get / get_triplets / get_rel_mapget(properties, ids)按 id 或属性条件查询节点返回EntityNode/ChunkNodeproperty_graph.py#L392-L452get_triplets(...)支持按实体名、关系类型、属性、id 过滤三元组默认返回上限 100 条自动排除Chunk节点并还原为[source, rel, target]结构property_graph.py#L454-L563get_rel_map(graph_nodes, depth2, limit30, ignore_relsNone)以给定节点为起点做深度感知的关系扩展用于检索时的图游走property_graph.py#L565。类级属性还声明了能力标志supports_structured_queries True、supports_vector_queries True即同时支持结构化查询与向量查询text_to_cypher_template使用 LlamaIndex 核心自带的默认 Cypher 生成提示模板DEFAULT_CYPHER_TEMPALTE。Schema 刷新机制refresh_schema()优先执行SHOW SCHEMA INFO;Memgraph 2.13 特性需以--schema-info-enabledtrue启动。若 Memgraph 报SchemaInfo disabled错误代码会自动降级回退到三条 Cypher 查询节点属性、关系属性、关系拓扑并把结果整理为structured_schema字典node_props/rel_props/relationships供 LLM 在生成 Cypher 时理解图结构property_graph.py#L213-L315。方案二MemgraphGraphStore 构建知识图谱如果你希望使用经典的KnowledgeGraphIndex基于 LLM 抽取三元组则使用MemgraphGraphStore。它实现 LlamaIndex 核心的GraphStore接口以Entity为默认节点标签存储三元组。完整示例从内存文档构建知识图谱以下示例同样来自 README.mdimport os import logging from llama_index.llms.openai import OpenAI from llama_index.core import Settings from llama_index.core import ( KnowledgeGraphIndex, SimpleDirectoryReader, StorageContext, ) from llama_index.graph_stores.memgraph import MemgraphGraphStore os.environ[OPENAI_API_KEY] YOUR_API_KEY # 替换为你的 OpenAI API Key logging.basicConfig(levellogging.INFO) llm OpenAI(temperature0, modelgpt-3.5-turbo) Settings.llm llm Settings.chunk_size 512 documents { doc1.txt: Python is a popular programming language known for its readability and simplicity. It was created by Guido van Rossum and first released in 1991. ..., doc2.txt: JavaScript is a high-level programming language primarily used for web development. It was created by Brendan Eich and first appeared in 1995. ..., doc3.txt: Java is a high-level, class-based, object-oriented programming language ... developed by James Gosling and first released by Sun Microsystems in 1995. ..., } for filename, content in documents.items(): with open(filename, w) as file: file.write(content) loaded_documents SimpleDirectoryReader(.).load_data() # 建立 Memgraph 连接请确保 Memgraph 已启动 username # Memgraph 用户名默认 password # Memgraph 密码默认 url # 连接地址例如 bolt://localhost:7687 database memgraph # 数据库名默认 memgraph graph_store MemgraphGraphStore( usernameusername, passwordpassword, urlurl, databasedatabase, ) storage_context StorageContext.from_defaults(graph_storegraph_store) index KnowledgeGraphIndex.from_documents( loaded_documents, storage_contextstorage_context, max_triplets_per_chunk3, ) query_engine index.as_query_engine( include_textFalse, response_modetree_summarize ) response query_engine.query(Tell me about Python and its uses) print(Query Response:) print(response)构造参数与初始化行为MemgraphGraphStore构造器kg_base.py#L32-L80参数默认值说明username/password/url必填Memgraph 认证与 Bolt 连接地址databasememgraph目标数据库名node_labelEntity三元组节点使用的标签名**kwargs—透传参数初始化时依次执行创建驱动并通过verify_connectivity()校验连接失败抛出ValueError调用refresh_schema()预取图结构执行CREATE CONSTRAINT ON (n:Entity) ASSERT n.id IS UNIQUE;创建唯一约束执行CREATE INDEX ON :Entity(id);创建索引加速查询。核心三元组操作MemgraphGraphStore通过以下方法完成图谱 CRUD写入三元组upsert_triplet(subj, rel, obj)用三次MERGE幂等创建主体、客体节点及关系边关系类型会被自动清洗为rel.replace( , _).upper()形式如is created by变为IS_CREATED_BYkg_base.py#L129-L136删除三元组delete(subj, rel, obj)按主客体 id 精确匹配删除关系边kg_base.py#L138-L145按主体查询get(subj)返回(关系类型, 客体 id)列表kg_base.py#L92-L102关系地图get_rel_map(subjs, depth2)使用可变长度模式[*1..{depth}]做多跳扩展返回{主体: [关系列表]}的扁平映射kg_base.py#L104-L127Schema 刷新refresh_schema()/get_schema(refreshFalse)基于schema.node_type_properties()、schema.rel_type_properties()与关系拓扑查询组装人类可读的 Schema 字符串供 LLM 理解图谱结构kg_base.py#L147-L170。通用查询入口query(query, param_map)是所有 Cypher 操作的统一入口它打开指定database的 session执行参数化查询并返回记录字典列表kg_base.py#L86-L90# 示例直接执行自定义 Cypher 查询 result graph_store.query(MATCH (n:Entity) RETURN n.id LIMIT 10)测试与接口契约验证集成包在 tests/test_graph_stores_memgraph.py 中验证了MemgraphGraphStore继承自 LlamaIndex 核心的GraphStore基类确保其满足GraphStore接口契约MemgraphPropertyGraphStore则继承自核心的PropertyGraphStore抽象类并实现其全部抽象方法。这意味着两个 Store 都可以直接与 LlamaIndex 的索引、检索、查询管线无缝组合。选型建议与注意事项新项目优先属性图MemgraphPropertyGraphStore同时支持结构化查询与向量查询实体 embedding 直接落库配合PropertyGraphIndex可同时获得图谱游走与向量召回的混合检索能力经典三元组场景用知识图谱MemgraphGraphStore实现简单直接适合三元组驱动的KnowledgeGraphIndex问答如示例中的tree_summarize响应模式连接配置默认数据库名为memgraph若实例启用了认证务必传入正确的username/passwordSchema 提示SHOW SCHEMA INFO需要 Memgraph 以--schema-info-enabledtrue启动否则实现会自动降级到备选查询无需额外配置版本前提本集成要求llama-index-core0.13.0,0.15与neo4j5.24.0,6升级依赖时请留意接口兼容性。总结Memgraph 集成包为 LlamaIndex 提供了两条完整的图存储落地路径MemgraphPropertyGraphStore面向新一代属性图 RAGMemgraphGraphStore面向经典知识图谱。两者都基于 Bolt 协议与 Cypher 实现代码层面通过neo4j驱动与批量MERGE/UNWIND保证写入幂等与性能并通过 Schema 刷新机制为 LLM 提供图结构上下文。结合 README 示例 与 源码实现你可以快速将文档、实体与关系沉淀进 Memgraph构建可查询、可推理的图增强 RAG 应用。【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考