如何使用python更新Cosmos Db中的记录? [英] How To Update Record in Cosmos Db using python?
问题描述
我想从cosmos db中读取记录,并使用python更新cosmos db中的相同记录.
I want to read record from cosmos db and update same record in cosmos db using python.
示例:
{
"id":"id-1",
"name":"mohit"
}
我想阅读上面的记录并将其更新为
I want to read the above record and update it to.
{
"id":"id-1",
"name":"Mohit Singh"
}
我发现链接很少,但似乎仅创建或删除记录,而没有更新现有记录:
I find few link but seems they only create or delete the record but not updating the existing record:
https://github.com/Azure/azure-cosmos-python#modify-container-properties
但无法获取如何更新现有记录的信息.
but unable to get how to update existing record.
在我的情况下,我想从cosmos db中读取所有记录,并更新一些值.
in my scenario i want to read all the record from cosmos db and update few value.
我如何在python中做到这一点.
how i can do it in python.
import os
import json
import azure.cosmos.cosmos_client as cosmos_client
COSMOS_DB_END_POINT = os.getenv("COSMOS_DB_END_POINT")
COSMOS_DB_MASTER_KEY = os.getenv("COSMOS_DB_MASTER_KEY")
COSMOS_DB_DATABASE_ID = os.getenv("COSMOS_DB_DATABASE_ID")
COSMOS_DB_COLLECTION_ID = os.getenv("COSMOS_DB_COLLECTION_ID");
client = cosmos_client.CosmosClient(COSMOS_DB_END_POINT, {'masterKey': COSMOS_DB_MASTER_KEY})
document_link = "dbs/" + COSMOS_DB_DATABASE_ID + "/colls/" + COSMOS_DB_COLLECTION_ID
for item in client.QueryItems(document_link,
'SELECT * FROM ' + COSMOS_DB_COLLECTION_ID,
{'enableCrossPartitionQuery': True}):
item['created'] += '123'
print(json.dumps(item, indent=True))
client.ReplaceItem(document_link, item, options=None)
推荐答案
The method you would want to use is ReplaceItem
. You will need to query the container to get the document (so that you have that document's self link), then call this method and pass the updated document.
这篇关于如何使用python更新Cosmos Db中的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!