ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

LlamaIndex 集成指南:基于阿里云 Tablestore 的 TablestoreKVStore 键值存储

LlamaIndex 集成指南:基于阿里云 Tablestore 的 TablestoreKVStore 键值存储 LlamaIndex 集成指南基于阿里云 Tablestore 的 TablestoreKVStore 键值存储【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index导读本文聚焦 LlamaIndex 仓库中llama-index-storage-kvstore-tablestore集成包的核心类TablestoreKVStore讲解如何以阿里云表格存储Tablestore / OTS作为 LlamaIndex 底层 KV 存储承载文档存储DocStore与索引存储IndexStore等持久化能力。读完本文你将掌握TablestoreKVStore的初始化参数、六大核心 API 的调用方式、collection 与 Tablestore 数据表之间的映射原理以及它与仓库内 docstore / index_store 配套模块的组合用法。TablestoreKVStore 是什么TablestoreKVStore是 LlamaIndex 官方为阿里云表格存储实现的键值存储适配器完整类定义位于 base.py模块入口在init.py。在类层级上它直接继承 LlamaIndex Core 的抽象基类BaseKVStore定义见 types.py因此必须实现put / aput / get / aget / get_all / aget_all / delete / adelete等标准方法并遵循默认 collection 为data的约定DEFAULT_COLLECTION见同一文件 types.py。从实现看TablestoreKVStore将 LlamaIndex 的collection集合直接映射为 Tablestore 的数据表Table将key 映射为表中主键为pkSTRING 类型的一行将value 字典映射为该行的属性列。这一映射关系贯穿put、get、get_all、delete、delete_all全部核心操作。安装与版本要求该集成包以独立子包形式存在于 llama-index-storage-kvstore-tablestore其 pyproject.toml 声明了如下关键约束Python3.10, 4.0依赖tablestore6.1.0阿里云官方 Python SDK以及llama-index-core0.13.0,0.15安装方式当前仓库为只读源码树实际使用时通过包管理器安装对应发行版pip install llama-index-storage-kvstore-tablestore安装完成后即可通过llama_index.storage.kvstore.tablestore导入from llama_index.storage.kvstore.tablestore import TablestoreKVStore初始化参数详解TablestoreKVStore.__init__的签名见 base.py如下参数类型是否可选说明tablestore_clienttablestore.OTSClient可选外部传入的 OTS 客户端一旦传入下面四个参数将被忽略endpointstr可选Tablestore 实例的 Endpoint 地址instance_namestr可选Tablestore 实例名称access_key_idstr可选阿里云 AccessKey IDaccess_key_secretstr可选阿里云 AccessKey Secret**kwargsAny可选透传给OTSClient的额外参数初始化逻辑非常直观若未提供外部tablestore_client则使用endpoint / access_key_id / access_key_secret / instance_name四元组内部创建OTSClient并显式指定retry_policytablestore.WriteRetryPolicy()写操作自动重试策略随后调用_update_collection()通过list_table()拉取当前实例下已有的全部表作为后续建表判断的缓存。一个完整的初始化示例from llama_index.storage.kvstore.tablestore import TablestoreKVStore kvstore TablestoreKVStore( endpointhttps://your-instance.cn-hangzhou.ots.aliyuncs.com, instance_nameyour_instance_name, access_key_idyour_access_key_id, access_key_secretyour_access_key_secret, )如果你已经持有自己配置好的 OTS 客户端也可以直接注入此时无需再提供凭据参数import tablestore client tablestore.OTSClient( https://your-instance.cn-hangzhou.ots.aliyuncs.com, your_access_key_id, your_access_key_secret, your_instance_name, ) kvstore TablestoreKVStore(tablestore_clientclient)说明以上参数中endpoint / instance_name / access_key_id / access_key_secret与测试用例中读取的环境变量一一对应见下文测试验证一节实际生产环境建议通过环境变量或密钥管理服务注入避免明文写死在代码中。核心 API 与数据流TablestoreKVStore的方法体系可划分为写路径、读路径、删路径三组。需要特别注意的是异步版本aput / aget / aget_all / adelete目前均直接抛出NotImplementedError见 base.py 等处因此该集成当前仅支持同步调用选用前需评估业务是否存在异步写入需求。写入putdef put(self, key: str, val: dict, collection: str DEFAULT_COLLECTION) - None写入流程base.py分为四步调用_flatten_dict_to_json_strings对 value 做预处理调用_create_collection_if_not_exist(collection)确保目标表存在构造主键[(pk, key)]将 value 的键值对转为属性列通过put_row(collection, row)写入 Tablestore。其中_flatten_dict_to_json_strings是数据序列化的关键base.py对于bool / bytearray / float / int / bytes / str等 Tablestore 原生可存储类型值原样保留其余类型如嵌套 dict、list、tuple、自定义对象统一通过json.dumps(value, ensure_asciiFalse)序列化为 JSON 字符串。这意味着嵌套结构、列表等复杂值都能安全落盘代价是读取时需按字符串还原。另外批量写入put_all继承自BaseKVStore的默认实现types.py在batch_size默认值为 1 时逐条调用put若传入其他batch_size则抛出NotImplementedError。读取get 与 get_alldef get(self, key: str, collection: str DEFAULT_COLLECTION) - Optional[dict] def get_all(self, collection: str DEFAULT_COLLECTION) - Dict[str, dict]getbase.py先确保表存在然后以[(pk, key)]为主键调用get_row(collection, primary_key, None, None, 1)取单行通过_parse_row还原 dict。若表尚未创建或行不存在会返回None——实现中还针对OTSParameterInvalid且错误信息含table not exist的服务端异常做了兜底返回None而非抛错。_parse_rowbase.py是反序列化的核心遍历属性列若取到的是字符串则尝试json.loads还原只有解析结果仍为dict / list / tuple时才保留还原值否则回退为原始字符串非字符串类型的值如数字、布尔原样返回。由此保证put的序列化在get时可逆。get_allbase.py则通过 Tablestore 的范围读取接口get_range实现全表扫描以INF_MIN为起始主键、INF_MAX为结束主键Direction.FORWARD正向遍历单次limit5000行、max_version1并通过next_start_primary_key循环翻页直至取完最终以{key: value_dict}的字典形式返回全部数据。删除delete 与 delete_alldef delete(self, key: str, collection: str DEFAULT_COLLECTION) - bool def delete_all(self, collection: str DEFAULT_COLLECTION) - Nonedeletebase.py构造主键[(pk, key)]后调用delete_row固定返回True即使行不存在也不会报错测试中kvstore.delete(not_existent)可正常执行。delete_allbase.py采用范围扫描 逐行删除策略与get_all相同的get_range分页遍历但将每页行列表交给_delete_rows逐行调用delete(key..., collection...)直到所有分页耗尽。自动建表机制无论put还是get都会先调用_create_collection_if_not_existbase.py它先查本地缓存再向服务端list_table()二次确认避免并发下的竞态若表确实不存在则用tablestore.TableMeta(collection, [(pk, STRING)])定义表结构主键列名固定为pk类型 STRING用tablestore.ReservedThroughput(tablestore.CapacityUnit(0, 0))设置预留读写吞吐为 0按量计费模式调用create_table(table_meta, tablestore.TableOptions(), reserved_throughput)建表刷新本地表清单缓存并sleep(5)等待 5 秒确保表进入可用状态后再继续写入。因此使用TablestoreKVStore时无需提前手工建表首次写入会自动完成表创建但要注意建表后的 5 秒等待属于固定延迟高并发冷启动场景需要纳入考量。在 DocStore 与 IndexStore 中的实际用法TablestoreKVStore是仓库内两个高层存储组件的底层依赖这也是它在 LlamaIndex 存储体系中的主要落地场景。TablestoreDocumentStore包 llama-index-storage-docstore-tablestore 中的 base.py 定义了TablestoreDocumentStore它继承 LlamaIndex Core 的KVDocumentStore将文档Node持久化到 Tablestore。其构造参数包括tablestore_kvstoreTablestoreKVStore实例必填namespace命名空间前缀默认llama_index_doc_store_node_collection_suffix/ref_doc_collection_suffix/metadata_collection_suffix分别对应节点、引用文档、元数据三张表的后缀默认data / ref_doc_info / metadata。from_config类方法支持直接以endpoint / instance_name / access_key_id / access_key_secret创建底层 KV Storeclear_all则依次清空三张表并删除内存中的文档索引。TablestoreIndexStore包 llama-index-storage-index-store-tablestore 中的 base.py 定义了TablestoreIndexStore继承KVIndexStore默认命名空间为llama_index_index_store_、collection 后缀为data同样提供from_config便捷构造与delete_all_index全量清理能力。组合示例from llama_index.storage.kvstore.tablestore import TablestoreKVStore from llama_index.storage.docstore.tablestore import TablestoreDocumentStore from llama_index.storage.index_store.tablestore import TablestoreIndexStore kvstore TablestoreKVStore( endpointhttps://your-instance.cn-hangzhou.ots.aliyuncs.com, instance_nameyour_instance_name, access_key_idyour_access_key_id, access_key_secretyour_access_key_secret, ) docstore TablestoreDocumentStore(tablestore_kvstorekvstore) index_store TablestoreIndexStore(tablestore_kvstorekvstore)从 mappings.json 可以看到Tablestore 在 LlamaIndex 中还有TablestoreVectorStore向量存储、TablestoreChatStore聊天存储等配套集成共同构成完整的 Tablestore 存储家族。测试验证仓库为该集成提供了完整的端到端测试见 test_storage_kvstore_tablestore.pytest_class断言TablestoreKVStore的 MRO 中包含BaseKVStore验证继承关系test_kvstore_basic写入并读取字符串值字典验证不存在的 collection 返回None验证delete返回Truetest_kvstore_delete写入后删除再读取确认得到None且删除不存在的 key 不抛异常test_kvstore_get_all写入含嵌套 dict、list、布尔的复杂值并验证往返一致随后验证get_all返回全部两条记录test_kvstore_put_all通过基类put_all批量写入两条记录并逐条校验test_delete_all写入 5 条记录后delete_all再get_all确认清空。测试依赖四个环境变量缺失时自动pytest.skipexport tablestore_end_pointhttps://your-instance.cn-hangzhou.ots.aliyuncs.com export tablestore_instance_nameyour_instance_name export tablestore_access_key_idyour_access_key_id export tablestore_access_key_secretyour_access_key_secret pytest llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-tablestore/tests/这些测试同时印证了前文的核心结论复杂类型的 JSON 序列化往返、collection 即数据表、默认 collection 为data、删除不存在 key 幂等安全。使用限制与注意事项综合源码与测试使用TablestoreKVStore时需注意以下边界异步 API 未实现aput / aget / aget_all / adelete均抛出NotImplementedError当前仅支持同步调用链建表固定主键结构每张表的主键恒为pkSTRINGvalue 中与pk同名的字段会被覆盖/冲突应避免将pk作为 value 的键复杂值序列化为 JSON 字符串嵌套 dict/list 等结构落盘后是字符串形态_parse_row仅在能解析为dict / list / tuple时才还原个别边界值如纯数字字符串读取时保持原字符串首次建表有 5 秒等待冷启动写入存在固定延迟且建表后本地缓存刷新批量接口受限put_all仅支持batch_size1逐条写入更高批次会抛异常get_all / delete_all为全表范围扫描每次请求limit5000行海量数据下耗时与请求次数会线性增长适合中小规模 KV 场景。小结TablestoreKVStore为 LlamaIndex 提供了面向阿里云表格存储的标准化 KV 持久化能力通过collection → 数据表、key → 主键行、value → 属性列复杂类型 JSON 化的映射设计完整实现了BaseKVStore的读写删接口并自动完成建表与按量吞吐配置。配合TablestoreDocumentStore、TablestoreIndexStore等上层封装可在不修改 LlamaIndex 主流程的前提下将索引与文档元数据持久化到阿里云 Tablestore适合已有阿里云基础设施、需要服务端持久化 KV 存储的 LlamaIndex 应用。【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表