8

This question relates to Microsoft.Azure.Cosmos v3.11.0.

The documentation of UpsertItemAsync doesn't specify the exact semantics for the "upsert" operation. In particular, is it an insert + replace, or insert + (partial) update? (I suspect the former, given that this issue is still open as of today.)

Mo B.
  • 5,307
  • 3
  • 25
  • 42

1 Answers1

24

CreateItemAsync will create a new item but will fail if there already is an item with the same ID.

ReplaceItemAsync will replace an existing item with the same ID but will fail if that item doesn't exists.

UpsertItemAsync combines the above two operations so it will either create or replace any item with the specified ID. So it's not an "insert + replace". Instead it's an "insert or replace".

Furthermore PatchItemAsync is now available so Cosmos also supports "partial updates".

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
  • 5
    Just to add a comment, the identity of a document is the ID + the Partition Key value (not just the ID). – Matias Quaranta Aug 04 '20 at 16:31
  • 1
    how would you get the ID of the item. Does it mean we have to Get the item for its ID and then do an Upsert? – saikumar Sep 24 '20 at 11:11
  • @saikumar: The three methods I have mentioned in my answer all operate on a single document. You have to provide the ID to identify the document to operate on (this is almost a pleonasm). If you have to perform a query (something like `select * from Container c where c.userName = 'saikumar'`) to get the ID, then yes, you will have to get the ID of the item by querying for the item. – Martin Liversage Sep 25 '20 at 09:21
  • Will the upsert also update the timestamp `_ts` of the document? – Good Night Nerd Pride Nov 02 '21 at 13:13
  • 1
    @GoodNightNerdPride Yes, Cosmos DB automactially adds a timestamp field called `_ts` everytime a document is created or updated – George Paoli Dec 10 '21 at 12:02
  • 1
    PatchItemAsync (partial update) is supported now: https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.container.patchitemasync – ZZY Feb 15 '22 at 09:14