LlamaIndex 存储层实战:使用 Azure Cosmos DB NoSQL KVStore 管理文档与索引元数据
【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index
导读
本文围绕 llama_index 存储层中基于 Azure Cosmos DB NoSQL 实现的AzureCosmosNoSqlKVStore,系统讲解其类方法、初始化参数、核心读写 API、异步方法支持边界、容器属性配置以及在BaseKVStore抽象体系中的定位。阅读完成后,你将能够在 LlamaIndex 应用中用连接字符串、账号密钥或 Azure AD 令牌三种方式接入 Cosmos DB NoSQL,并正确选择同步/异步方法完成 KV 数据的持久化读写,同时了解它与 DocStore、IndexStore 等其他存储组件的协作方式。
一、AzureCosmosNoSqlKVStore 在 LlamaIndex 存储体系中的定位
LlamaIndex 的 KVStore 层承担着键值数据的持久化职责,其抽象基类BaseKVStore定义在 types.py 中,要求所有实现提供put、get、get_all、delete及对应的异步版本aput、aget、aget_all、adelete,并约定默认 collection 名为data。
AzureCosmosNoSqlKVStore位于 base.py,它继承自BaseKVStore,将 Azure Cosmos DB NoSQL API 作为底层持久化介质,用 Cosmos 的 Database 对应 LlamaIndex 的数据库实例、Container 承载 KV 数据。从仓库结构看,Cosmos NoSQL 集成同时提供了同系列的 DocStore 与 IndexStore 实现,KVStore 是其中被 ChatStore、Memory 等上层模块复用的基础组件。
该集成的包信息可在 pyproject.toml 中确认:包名为llama-index-storage-kv-store-azurecosmosnosql,版本 1.3.0,依赖azure-cosmos>=4.7.0,<5、azure-identity>=1.7.1,<2以及llama-index-core>=0.13.0,<0.15。
二、安装与导入
安装该集成包后即可从llama_index.storage.kvstore.azurecosmosnosql导入AzureCosmosNoSqlKVStore(导出声明见init.py):
from llama_index.storage.kvstore.azurecosmosnosql import AzureCosmosNoSqlKVStore注意:本文仓库为源码形态,实际使用时需按常规 Python 包方式安装该集成包及其依赖(
azure-cosmos、azure-identity等),并确保 Cosmos DB NoSQL 账号可访问。
三、核心类方法与初始化参数
AzureCosmosNoSqlKVStore在构造时会将传入的CosmosClient保存在PrivateAttr中,并自动完成数据库与容器的“不存在则创建”逻辑:
- 通过
create_database_if_not_exists创建数据库,默认名KVStoreDB; - 通过
create_container_if_not_exists创建容器,默认名KVStoreContainer,其中partition_key 是必填项(源码中直接通过cosmos_container_properties["partition_key"]访问)。
3.1 构造器参数详解
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
cosmos_client | CosmosClient | 无 | azure-cosmos 的客户端实例,通常由下面三个类方法之一创建 |
chat_db_name | str | "KVStoreDB" | Cosmos 数据库名称,不存在时自动创建 |
chat_container_name | str | "KVStoreContainer" | Cosmos 容器名称,不存在时自动创建 |
cosmos_container_properties | Dict[str, Any] | None | 容器创建属性,至少需含partition_key |
cosmos_database_properties | Dict[str, Any] | None | 数据库创建属性,如offer_throughput等 |
cosmos_container_properties支持键包括:partition_key(必填)、indexing_policy、default_ttl、offer_throughput、unique_key_policy、conflict_resolution_policy、analytical_storage_ttl、computed_properties、etag、match_condition、session_token、initial_headers。其中default_ttl可设置数据自动过期时间,offer_throughput用于配置吞吐量(RU/s),unique_key_policy用于保证键唯一性,这些参数都会原样透传给 azure-cosmos SDK 的容器创建方法。
cosmos_database_properties支持offer_throughput、session_token、initial_headers、etag、match_condition。
3.2 三种客户端创建方式
方式一:连接字符串
kv_store = AzureCosmosNoSqlKVStore.from_connection_string( connection_string="AccountEndpoint=...;AccountKey=...;", )方式二:账号 Endpoint + Key
kv_store = AzureCosmosNoSqlKVStore.from_account_and_key( endpoint="https://<account-name>.documents.azure.com:443/", key="<primary-key>", )方式三:Azure AD 令牌(AAD)
kv_store = AzureCosmosNoSqlKVStore.from_aad_token( endpoint="https://<account-name>.documents.azure.com:443/", )第三种方式内部使用azure.identity.DefaultAzureCredential()获取凭据,适合在 Azure 托管环境(如 VM、Functions、AKS)中以托管身份免密钥接入;三种方式均支持传入chat_db_name、chat_container_name、cosmos_container_properties、cosmos_database_properties四个可选参数。
四、核心 API:KV 数据读写全流程
AzureCosmosNoSqlKVStore将 KV 数据映射为 Cosmos 容器内的文档:写入时以{"id": key, "messages": val}结构创建条目,读取时返回文档中的messages字段。
4.1 写入 put
kv_store.put(key="session-1", val={"user": "alice", "history": [...]})4.2 读取 get / get_all
value = kv_store.get("session-1") # 返回 dict,键不存在时返回 {} all_items = kv_store.get_all() # 返回 {id: 文档} 的映射get_all通过read_all_items()遍历容器,返回以文档id为键的完整字典。
4.3 删除 delete
deleted = kv_store.delete("session-1") # 成功返回 True,失败记录日志并返回 False4.4 异步方法的边界
该类目前未实现异步方法:aput、aget、aget_all、adelete均直接抛出NotImplementedError(见 base.py)。因此在异步代码路径中请使用同步方法配合线程池,或等待该集成后续版本补齐异步实现。同理,BaseKVStore的put_all默认仅支持batch_size=1,逐条调用put。
五、作为 KVStore 的验证与组合使用
仓库测试 test_storage_azurecosmosnosql_kv_store.py 验证了AzureCosmosNoSqlKVStore确实继承自BaseKVStore,确认其符合 LlamaIndex 存储抽象契约。
由于 ChatStore、Memory 等模块依赖 KVStore 的put/get接口,可将本实现注入这些上层组件以复用 Cosmos 持久化;同目录下的 docstore 与 index_store 也基于同一 Cosmos 账号体系,可用于完整落地文档与索引元数据的云原生存储方案。
六、使用注意事项
- partition_key 必填:创建容器时必须提供,否则构造阶段即抛 KeyError;
- 默认库/容器名:
KVStoreDB/KVStoreContainer,多环境隔离时建议显式指定不同名称; - 数据过期:需要自动清理时设置
cosmos_container_properties["default_ttl"]; - 异步支持缺失:当前版本异步方法不可用,编程时避免在 async 场景直接调用;
- 依赖版本约束:
azure-cosmos>=4.7.0,<5、azure-identity>=1.7.1,<2、llama-index-core>=0.13.0,<0.15,升级依赖前请核对兼容性。
七、总结
AzureCosmosNoSqlKVStore是 LlamaIndex 存储层中面向 Azure 云原生的 KV 持久化实现,继承 BaseKVStore 统一契约,支持连接字符串、账号密钥、AAD 三种认证方式,通过put/get/get_all/delete完成文档级 KV 操作。其数据库、容器自动创建机制与容器属性透传设计,使其可灵活适配吞吐、TTL、分区键等生产级需求;配合同系列 DocStore、IndexStore 可实现完整的数据持久化闭环。使用前请重点确认容器分区键配置与异步方法边界,以获得稳定可控的存储体验。
【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考