Mohit Singh
Mohit Singh

Reputation: 477

How To Update Record in Cosmos Db using python?

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)

Upvotes: 1

Views: 7869

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136256

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.

Upvotes: 2

Related Questions