ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

LlamaIndex × Amazon Neptune 图存储集成实战:四大 Graph Store 类与 openCypher 查询全解析

2026/9/11 20:36:07 拓冰建站 浏览量
LlamaIndex × Amazon Neptune 图存储集成实战:四大 Graph Store 类与 openCypher 查询全解析 LlamaIndex × Amazon Neptune 图存储集成实战四大 Graph Store 类与 openCypher 查询全解析【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index本文围绕 LlamaIndex 官方 API 参考文档中llama_index.graph_stores.neptune模块的四个核心类展开系统讲解如何在 LlamaIndex 中把 Amazon NeptuneNeptune Database 与 Neptune Analytics接入知识图谱索引Knowledge Graph Index与属性图索引Property Graph Index涵盖安装配置、客户端创建、openCypher 查询、Schema 自动刷新与向量检索等关键技术点。读完本文你将掌握基于源码级别的 Neptune 图存储集成原理并能够直接在自己的 LlamaIndex 项目中配置和调用这四类 Graph Store。从 API 参考页看 Neptune 集成模块的组成本仓库的 API 参考文档 docs/api_reference/api_reference/storage/graph_stores/neptune.md 使用 mkdocstrings 指令自动生成模块文档明确列出了四个公开成员类NeptuneAnalyticsGraphStoreNeptuneAnalyticsPropertyGraphStoreNeptuneDatabaseGraphStoreNeptuneDatabasePropertyGraphStore这四个类分别组合了「两种存储引擎」Neptune Database 与 Neptune Analytics与「两种图存储抽象」Knowledge Graph Store 与 Property Graph Store两个维度实际实现在集成包llama-index-graph-stores-neptune中。包内__init__.py见 llama-index-integrations/graph_stores/llama-index-graph-stores-neptune/llama_index/graph_stores/neptune/init.py同时导出了异常类NeptuneQueryException用于统一包装查询过程中的错误。背景Neptune Database 与 Neptune Analytics 的定位根据集成包 README.md 的描述Neptune Database面向生产环境的无服务器图数据库官方定位适用于需要扩展到每秒 10 万次查询、多可用区Multi-AZ高可用与多区域multi-Region部署的场景典型应用包括社交网络、欺诈告警与 Customer 360 等图数据库工作负载。Neptune Analytics内存级分析型图引擎用于快速分析存量图数据库或数据湖中的图数据集借助流行的图分析算法与低延迟分析查询获得洞察与趋势。集成包的目标是把两种 Neptune 引擎都接入 LlamaIndex 图存储抽象层并统一使用 openCypher 查询语言与 LlamaIndex 的图索引交互。README 给出的类划分如下存储引擎Property Graph StoreKnowledge Graph StoreNeptune DatabaseNeptuneDatabasePropertyGraphStoreNeptuneDatabaseGraphStoreNeptune AnalyticsNeptuneAnalyticsPropertyGraphStoreNeptuneAnalyticsGraphStore安装与依赖根据 README安装命令为pip install llama-index llama-index-graph-stores-neptune从 pyproject.toml 可以确认运行依赖boto31.34.40,2AWS SDK用于创建 Neptune 客户端llama-index-core0.13.0,0.15提供GraphStore/PropertyGraphStore抽象基类与LabelledNode、EntityNode、ChunkNode、Relation等数据结构要求 Python3.10,4.0。需要注意版本下限源码neptune.py在捕获到 boto3 的UnknownServiceError时会提示「Neptune Database requires a boto3 version 1.34.40 or greater」即低于 1.34.40 的 boto3 无法识别neptunedata与neptune-graph这两个服务接口。四大核心类逐一拆解1. Knowledge Graph Store面向三元组的传统图存储Knowledge Graph Store 对应 LlamaIndex 核心模块中的GraphStore协议定义于 llama-index-core/llama_index/core/graph_stores/types.py以「主语-关系-宾语」三元组triplet为基本操作单位。NeptuneDatabaseGraphStoreNeptune Database 知识图谱存储构造参数见 database.py参数类型默认值说明hoststr必填Neptune 数据库的终端节点地址portint8182连接端口use_httpsboolTrueTrue 使用 httpsFalse 使用 httpclientAnyNone若传入则直接复用该 boto3 客户端不再自行创建credentials_profile_nameOptional[str]NoneAWS 凭证 profile 名称region_nameOptional[str]NoneAWS 区域signboolTrueTrue 对请求做 SigV4 签名False 则使用UNSIGNED签名版本node_labelstrEntity节点标签写入与查询三元组时使用其query()方法直接调用 boto3neptunedata客户端的execute_open_cypher_query将参数以 JSON 字符串形式传入返回results任何异常都会被包装为NeptuneQueryException。NeptuneAnalyticsGraphStoreNeptune Analytics 知识图谱存储构造参数见 analytics.py参数类型默认值说明graph_identifierstr必填Neptune Analytics 图标识必须是g-XXXXXXXXXX形式clientAnyNone复用的 boto3 客户端credentials_profile_nameOptional[str]NoneAWS 凭证 profileregion_nameOptional[str]NoneAWS 区域node_labelstrEntity节点标签其query()使用neptune-graph客户端的execute_query显式指定languageOPEN_CYPHER并通过graphIdentifier定位目标图最后从payload流中读取并解析 JSON 得到results。注意graph_identifier有严格校验必须以g-开头且不含.否则直接抛出ValueError。共享抽象基类NeptuneBaseGraphStore两个 Knowledge Graph Store 都继承自 base.py 中的NeptuneBaseGraphStore继承自核心模块的GraphStore协议基类提供了完整的三元组操作实现get(subj)查询指定主体的所有出边关系MATCH (n1:Entity)-[r]-(n2:Entity) WHERE n1.id $subjget_rel_map(subjs, depth2, limit30)以可变深度[*1..{depth}]遍历子图按主体聚合扁平化的关系列表upsert_triplet(subj, rel, obj)用MERGE幂等创建节点与关系关系名会被去空格、去反引号并转大写delete(subj, rel, obj)先删关系再DETACH DELETE孤立实体get_schema(refreshFalse)调用refresh_schema生成 Schema 字符串支持强制刷新。单元测试 tests/test_graph_stores_neptune.py 验证了继承关系NeptuneAnalyticsGraphStore与NeptuneDatabaseGraphStore均继承NeptuneBaseGraphStore而NeptuneBaseGraphStore继承自核心GraphStore协议。2. Property Graph Store面向节点、关系与向量的属性图存储Property Graph Store 对应核心模块的PropertyGraphStore抽象类定义于 llama-index-core/llama_index/core/graph_stores/types.py以LabelledNode含EntityNode、ChunkNode与Relation为操作对象同时声明supports_structured_queries True并内置text_to_cypher_template默认DEFAULT_CYPHER_TEMPALTE支持自然语言到 Cypher 的结构化查询转换。NeptuneDatabasePropertyGraphStore构造参数与NeptuneDatabaseGraphStore相同host、port8182、use_httpsTrue、signTrue等supports_vector_queries False不支持向量查询调用vector_query()直接抛NotImplementedErrorstructured_query()通过execute_open_cypher_query执行 openCypherupsert_nodes()将节点按类型分流ChunkNode用MERGE (c:Chunk {id})写入文本与属性EntityNode用MERGE (e:__Node__ {id})写入名称、属性并打上__Entity__标签与具体标签若存在triplet_source_id属性还会通过MENTIONS关系把实体关联回源 Chunk 节点_get_summary()调用 Neptune 的 Property Graph Summary API要求引擎版本1.2.1.0低于该版本会抛出带提示信息的NeptuneQueryException。NeptuneAnalyticsPropertyGraphStore构造参数与NeptuneAnalyticsGraphStore相同graph_identifier必填supports_vector_queries True支持向量查询这也是 Analytics 版与 Database 版属性图存储最关键的差异vector_query()的实现展示了 Neptune Analytics 的向量能力先按过滤条件匹配__Entity__节点再依次调用neptune.algo.vectors.get(e)获取嵌入、neptune.algo.vectors.topKByNode(e)按相似度取 TopK最后按score降序返回(nodes, scores)upsert_nodes()在写入 Chunk 与 Entity 时若节点带有embedding属性会调用neptune.algo.vectors.upsert(c, e)将向量一并写入索引_get_summary()调用get_graph_summary(graphIdentifier..., modedetailed)获取详细图拓扑摘要。共享抽象基类NeptuneBasePropertyGraphbase_property_graph.py 定义了NeptuneBasePropertyGraph继承核心PropertyGraphStore并约定两个内部标签常量BASE_ENTITY_LABEL __Entity__、BASE_NODE_LABEL __Node__。基类提供get(properties, ids, exact_matchTrue)按 id 或属性精确/模糊匹配查询节点自动区分返回ChunkNode含text属性或类型为空与EntityNodeget_triplets(entity_names, relation_names, properties, ids)查询实体及其出边三元组返回[source, rel, target]结构get_rel_map(graph_nodes, depth2, limit30, ignore_relsNone)深度感知的关系遍历默认排除MENTIONS关系即只保留实体间语义关系upsert_relations(relations)按Relation列表逐条MERGE关系并合并属性delete(entity_names, relation_names, properties, ids)支持按实体名、id、关系名或属性条件删除get_schema(refreshFalse)/get_schema_str(refreshFalse)返回结构化的structured_schema或人类可读的 Schema 字符串。openCypher 查询与底层调用链两种引擎统一使用 openCypher 作为查询语言但底层调用链不同Neptune DatabaseNeptuneDatabaseGraphStore.query/NeptuneDatabasePropertyGraphStore.structured_query→ boto3neptunedata.execute_open_cypher_query(openCypherQuery..., parametersjson.dumps(...))Neptune AnalyticsNeptuneAnalyticsGraphStore.query/NeptuneAnalyticsPropertyGraphStore.structured_query→ boto3neptune-graph.execute_query(graphIdentifier..., queryString..., parameters..., languageOPEN_CYPHER)响应从payload流读取并json.loads解析。从源码中的 Cypher 模板可以归纳出该集成约定的图数据模型可据此理解数据落盘结构节点统一使用id属性标识实体另带name属性实体打__Entity__标签与具体业务标签Chunk 节点打Chunk标签Chunk 与实体之间用MENTIONS关系连接get_rel_map默认过滤该关系以便只返回实体间关系属性写入统一通过 openCypher 内置函数removeKeyFromMap剔除空值键。Schema 自动刷新机制两类存储都依赖「Summary API」实现 Schema 的自发现Neptune Database 调用get_propertygraph_summary()取payload.graphSummaryNeptune Analytics 调用get_graph_summary(graphIdentifier..., modedetailed)取graphSummary。refresh_schema()见 neptune.py随后基于摘要执行三组探测查询_get_triples对每个边标签采样MATCH (a)-[e:label]-(b) LIMIT 3000生成(:A)-[:E]-(:B)形式的三元组 Schema_get_node_properties对每个节点标签采样属性并通过类型映射{str: STRING, float: DOUBLE, int: INTEGER, list: LIST, dict: MAP, bool: BOOLEAN, datetime: DATETIME}推断属性类型字符串属性还会尝试用dateutil.parser识别为 DATETIME_get_edge_properties对每个边标签执行同样流程。最终生成两个产物人类可读的schema_str描述节点属性、关系属性与关系三元组和结构化的structured_schema含node_labels、edge_labels、node_properties、edge_properties、triples。get_schema(refreshFalse)仅在 Schema 为空或显式要求刷新时才会重新探测。异常处理NeptuneQueryException所有查询与摘要调用都通过NeptuneQueryException统一收敛错误见 neptune.py接受字符串或字典两种入参从字典中提取message与details字段缺失时回退为unknown提供get_message()与get_details()访问器常见触发场景包括查询执行失败、Summary API 不可用引擎版本过低、Summary 响应格式非法等。客户端创建细节与注意事项两个create_*_client工厂函数同样位于 neptune.py负责 boto3 客户端装配值得注意的实现细节Database 客户端endpoint_url由protocol://host:port拼装协议取决于use_httpssignFalse时通过botocore.Config(signature_versionUNSIGNED)关闭 SigV4 签名凭证来自传入的credentials_profile_name或默认凭证链Analytics 客户端固定使用neptune-graph服务并配置retries{total_max_attempts: 1, mode: standard}与read_timeoutNone长时间运行的分析查询不设读取超时未安装 boto3 时抛出ModuleNotFoundError(Could not import boto3 python package. Please install it with pip install boto3.)凭证无效时抛出带提示的ValueError。验证与测试集成包的 tests/test_graph_stores_neptune.py 通过三个测试用例验证了类层次结构两个实体 Graph Store 类均继承NeptuneBaseGraphStore而NeptuneBaseGraphStore继承核心GraphStore协议。Property Graph 侧的继承关系同理NeptuneBasePropertyGraph继承核心PropertyGraphStore抽象类可结合 llama-index-core/llama_index/core/graph_stores/types.py 继续深入阅读。小结llama_index.graph_stores.neptune模块用四个类完整覆盖了 Amazon Neptune 两种引擎 × 两种图存储抽象的组合。选择建议可以归纳为需要生产级高可用、与现有图数据库工作负载对齐 →Neptune Database系列需要内存级图分析、大规模图数据快速洞察 →Neptune Analytics系列需要向量检索与属性图能力 →Property Graph Store系列其中 Analytics 版支持向量查询Database 版不支持需要与知识图谱索引三元组对接 →Knowledge Graph Store系列。在动手之前请确保 boto3 版本 ≥ 1.34.40、Python ≥ 3.10并按需配置 AWS 凭证profile 或默认凭证链Neptune Database 的 Summary API 需要引擎版本 ≥ 1.2.1.0。后续可在集成包 README 与源码中继续挖掘 openCypher 模板、向量算法neptune.algo.vectors.*等更深层的用法。【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考