Azure Cosmos DB使用Python创建指定参数容器失败求助
Cosmos DB创建MultiHash类型分区键容器报BadRequest错误的解决方法
错误原因
你遇到的BadRequest错误核心原因是:MultiHash类型的多路径分区键仅支持Azure Cosmos DB API for MongoDB,而你当前使用的是Core (SQL) API(默认Python SDK针对的是该API),Core SQL API不支持多路径分区键的配置方式。
解决方案
方案1:Core (SQL) API下使用合成分区键
Core SQL API仅支持单个分区键路径,要实现多字段组合分区,需创建一个合成的分区键字段(比如combined_location),将state、city、zipcode拼接后存入该字段。修正后的代码如下:
from azure.cosmos import CosmosClient, PartitionKey, exceptions # 假设已完成client和database的初始化 location_container_name = "locations" try: container = database.create_container( id=location_container_name, partition_key=PartitionKey(path="/combined_location") ) print("容器创建成功") except exceptions.CosmosResourceExistsError: # 修复原代码变量未定义问题:将container_name改为location_container_name container = database.get_container_client(location_container_name) print("容器已存在,获取客户端成功")
插入文档时需手动添加合成字段:
item = { "id": "item1", "state": "WA", "city": "Redmond", "zipcode": "98052", "combined_location": "WA-Redmond-98052" } container.create_item(body=item)
方案2:切换为API for MongoDB使用MultiHash分区键
若必须使用原生多路径分区键,需确保你的Cosmos DB账户为API for MongoDB类型,使用pymongo SDK创建容器:
from pymongo import MongoClient # 替换为你的Mongo API连接字符串 client = MongoClient("mongodb://<账户名>:<账户密钥>@<账户名>.mongo.cosmos.azure.com:10255/?ssl=true&retrywrites=false&maxIdleTimeMS=120000&appName=@<账户名>@") database = client["testdatabase"] location_container_name = "locations" if location_container_name not in database.list_collection_names(): database.create_collection( location_container_name, partitionKey={ "paths": ["/state", "/city", "/zipcode"], "kind": "MultiHash" } ) print("集合创建成功") else: container = database[location_container_name] print("集合已存在")
额外注意
原代码中存在变量未定义问题:except块里的container_name未声明,需替换为location_container_name,否则会触发NameError。
内容的提问来源于stack exchange,提问作者Raghu Monavarthi
相关产品推荐
相关产品推荐

