1

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)
Mohit Singh
  • 401
  • 1
  • 10
  • 30

1 Answers1

2

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.

Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241
  • getting this error azure.cosmos.errors.HTTPFailure: Status code: 401 {"code":"Unauthorized","message":"The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'put\ncolls\ndbs/dptest/colls/test\nthu, 12 mar 2020 16:43:25 gmt\n\n'\r\nActivityId: 68d7e503-31a0-4csc-dea0-5b8713cd90f3, Microsoft.Azure.Documents.Common/2.10.0"} – Mohit Singh Mar 12 '20 at 16:44
  • please find the code in the above question https://github.com/Azure/azure-cosmos-python i am using this one – Mohit Singh Mar 12 '20 at 16:57
  • `document_link` in your code is actually `collection_link`. For updating the document, you would need to find similar thing in your `item` variable (I think it is `_self`) which represents the document's self link. – Gaurav Mantri Mar 12 '20 at 17:05
  • got it worked , thanks i did like this client.ReplaceItem(item['_self'], item, options=None) – Mohit Singh Mar 12 '20 at 17:12
  • @MohitSingh can you kindly post this working code of yours if you still have it? Else, can you at the very least post a working example code if possible? – mang4521 Apr 05 '22 at 14:57