我有一个脚本,可以获取某个记录(如果存在),并在使用
replace_item
或 upsert_item
在数据库中更新它之前修改其属性。如果我获取整个记录,更改属性并将该记录用作项目和正文,则它可以正常工作。
但是,如果我决定只获取文档的 ID(以保存在 RU 上),将 id 放入具有足够属性的新对象中,然后使用 id 和新文档进行更新,则文档会莫名其妙地被删除。
有问题的代码变体可以在下面找到:
dbList = list(dbContainer.query_items(
query="SELECT c.id FROM c WHERE c.something = @something",
parameters=[
dict(name='@something', value=whatever)
],
enable_cross_partition_query=True
))
if dbList:
# Update the item if it exists, considering we must have only one
record = dbList[0]
record['property'] = newProperty
try:
container.replace_item(item=record['id'], body=record)
except exceptions.CosmosHttpResponseError as e:
print(f"Failed to update record. Details: {e.message}")
我尝试使用
upsert_item
而不是 replace_item
但我得到了相同的结果。通过 ID 选择并设置 item=record
给我一个 KeyError。
是的@S.Ptr,我同意David所说的,
replace_item()
无法使用分区键值,并且如果没有正确的分区键,则无法执行替换操作。如果分区键是 id
并尝试更改其值,则会抛出错误。下面是成功运行的代码,如果找到搜索的项目,然后将其替换为新值,如下面的输出所示。
from azure.cosmos import CosmosClient, exceptions
endpoint = "*****"
key = "*****"
client = CosmosClient(endpoint, key)
database_name = "firstDb"
container_name = "firstCont1"
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)
dbList = list(container.query_items(
query="SELECT * FROM c WHERE c.something = @something",
parameters=[
dict(name='@something', value="value1")
],
enable_cross_partition_query=True
))
if dbList:
record = dbList[0]
record['property'] = "updated_value1"
try:
container.replace_item(item=record['id'], body=record)
print(f"Document updated successfully: {record}")
except exceptions.CosmosHttpResponseError as e:
print(f"Failed to update document. Details: {e.message}")
else:
print("No document found with the specified query.")
存储在 Azure Cosmos DB 容器中的数据:
[
{
"id": "1",
"something": "value1",
"property": "initial_value1"
},
{
"id": "2",
"something": "value2",
"property": "initial_value2"
},
{
"id": "3",
"something": "value3",
"property": "initial_value3"
}
]
执行代码后 Azure Cosmos DB 中的数据:
输出:
文档更新成功:
[
{
"id": "1",
"something": "value1",
"property": "updated_value1"
},
{
"id": "2",
"something": "value2",
"property": "initial_value2"
},
{
"id": "3",
"something": "value3",
"property": "initial_value3"
}
]