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

Azure Cosmos DB:用Python创建无分区键容器是否可行?

关于Azure Cosmos DB创建无分区键容器的问题

核心结论

可以创建无需用户指定分区键的容器,这类容器本质是单分区容器,由系统自动管理隐含的分区键,但存在以下限制:

  • 最大存储容量为10GB
  • 最大吞吐量上限为10,000 RU/s
  • 无法后续扩容为多分区容器,仅适合小规模数据场景

脚本修正说明

你提供的脚本中,partition_key=None的写法不符合Azure Cosmos DB Python SDK(v4+)的要求,会触发参数错误。正确的创建方式有两种:

方式1:不指定partition_key参数

直接省略分区键参数,SDK会默认创建单分区容器:

from azure.cosmos import CosmosClient
import urllib3
urllib3.disable_warnings()

endpoint = "https://test-ck.documents.azure.com:443/"
account_key = "YOUR_ACCOUNT_KEY"

client = CosmosClient(url=endpoint, credential=account_key)
database_name = "test"
container_name = "testcontainer"

try:
    print("Connection made")
    client.create_database_if_not_exists(database_name)
    database = client.get_database_client(database_name)

    # 不指定partition_key,默认创建单分区容器
    container = database.create_container_if_not_exists(container_name)
    print(f"Container '{container_name}' created as single-partition container (no user-specified partition key)")
except Exception as e:
    print(f"An error occurred: {e}")

# 插入示例记录
sample_records = [
    {"id": str(i), "name": f"Person{i}", "age": 25 + i} for i in range(1, 51)
]

for record in sample_records:
    try:
        container.upsert_item(record)
        print(f"Inserted item with id: {record['id']}")
    except Exception as e:
        print(f"Error inserting item: {e}")

方式2:显式指定系统默认分区键

如果需要明确声明使用系统隐含的分区键/_partitionKey,可以这样写:

from azure.cosmos import CosmosClient, PartitionKey
import urllib3
urllib3.disable_warnings()

# 省略其他相同代码...

container = database.create_container_if_not_exists(
    id=container_name,
    partition_key=PartitionKey(path="/_partitionKey")
)

这种方式下,你插入的文档也不需要包含_partitionKey字段,系统会自动处理。

注意事项

  • 单分区容器无法通过Azure门户直接创建,必须通过SDK或Azure CLI/ARM模板等方式创建
  • 若你的数据量或吞吐量需求超过单分区限制,建议创建多分区容器并指定自定义分区键

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:07:35