
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__?;愄峁ゞet(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.*等更深層的用法?!久赓M下載鏈接】llama_indexLlamaIndex is the leading document agent and OCR platform項目地址: https://gitcode.com/GitHub_Trending/ll/llama_index創作聲明:本文部分內容由AI輔助生成(AIGC),僅供參考