How To Update Record in Cosmos Db using python?

元气小坏坏 提交于 2021-02-11 16:42:19

问题


I want to read record from cosmos db and update same record in cosmos db using python.

example:

{
  "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.

in my scenario i want to read all the record from cosmos db and update few value.

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)

回答1:


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.



来源:https://stackoverflow.com/questions/60652844/how-to-update-record-in-cosmos-db-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!