Skip to content
Advertisement

How to update a property in an Entity in Cosmos table API using Python

I have the below table in CosmosDB.

PartitionKey  Rowkey  Group  Salary
John          HR      A      100000
Mark          DOC     B      200000

I want to update the Salary property in the first entity. When I tried to update the salary property in the first entity, the complete entity is being replaced instead of updating the salary property.

Could someone let me know how to update an property in a entity in CosmosDB table API.

from azure.data.tables import TableServiceClient
from datetime import datetime


my_entity = {
   "PartitionKey" : "John",
    "RowKey" : "HR",
    "Group": "A",
    "Salary": 100000
  
}
table_service_client = TableServiceClient.from_connection_string(conn_str="")
table_client = table_service_client.get_table_client(table_name="my_table")

entity = table_client.create_entity(entity=my_entity)


created = table.get_entity(partition_key=my_entity["PartitionKey"], row_key=my_entity["RowKey"])
created["Salary"] = "200"
table.update_entity(mode=UpdateMode.REPLACE, entity=created)

Advertisement

Answer

Please try by changing the following lines of code:

created = table.get_entity(partition_key=my_entity["PartitionKey"], row_key=my_entity["RowKey"])
created["Salary"] = "200"
table.update_entity(mode=UpdateMode.REPLACE, entity=created)

with

created = table_client.get_entity(partition_key=my_entity["PartitionKey"], row_key=my_entity["RowKey"])
created["Salary"] = "200"
table_client.update_entity(mode=UpdateMode.MERGE, entity=created)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement