You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现Cosmos DB Point Read以将RU消耗降至1?

Cosmos DB Point Read 实现与索引策略说明

一、索引策略是否需要调整?

不需要调整。Point Read操作不依赖索引——它直接通过分区键(npi)和文档ID(id)定位到具体物理位置读取数据,不管当前索引策略如何配置都能正常执行,且始终消耗1 RU。你的当前索引策略是默认全路径包含索引,完全不影响Point Read的执行。

二、Python 实现 Point Read 操作

使用 Azure Cosmos DB Python SDK(azure-cosmos 包),通过 read_item 方法即可实现Point Read,具体步骤如下:

1. 安装依赖

先确保安装官方SDK:

pip install azure-cosmos

2. 代码示例

from azure.cosmos import CosmosClient

# 初始化Cosmos客户端
endpoint = "你的Cosmos DB账户端点"
account_key = "你的Cosmos DB账户密钥"
client = CosmosClient(endpoint, account_key)

# 获取目标数据库和容器
database = client.get_database_client("你的数据库名称")
container = database.get_container_client("你的容器名称")

# 执行Point Read:必须传入文档ID和分区键值(类型需与文档一致)
target_id = "1437156155"
target_partition_key = 1437156155  # 注意此处是整数,要匹配文档中npi的类型

try:
    document = container.read_item(item=target_id, partition_key=target_partition_key)
    print("读取到的文档内容:", document)
except Exception as e:
    print("读取失败:", str(e))

关键注意点

  • 必须同时提供文档ID和分区键值,且两者的数据类型要与文档中的完全匹配(比如示例中npi是整数,不能传入字符串类型的键值)。
  • 该操作直接命中存储位置,RU消耗固定为1,比原查询的2.83 RU更高效。

内容的提问来源于stack exchange,提问作者GoneCase123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 10:55:15