Tuesday, August 13, 2019

How unique is Azure Cosmos DB Unique Keys?


     I wrote about Unique Keys and tried to explain how they work in one of my earlier post. It's common to use SQL Server's Primary Key or Unique Indexes to explain Unique Keys of Azure Cosmos DB. If you have a Primary Key in a table in SQL Server, the key you defined cannot be in that table more than once. By adding a unique index or unique constraint in a table, you guarantee that no duplicate values can be in your table. The key word in both of those statement is the TABLE.
Azure CosmosDB Unique Keys do not work like Primary Key or Unique Indexes/Constraints. A Unique Key is unique in defined LOGICAL PARTITION. Not the whole Container!

     Let's see how unique the unique keys by looking at the following example, I have a Hotel named Savran Hotel and I am using Cosmos DB to track my reservations. I use Room Number as my partition, because the way my system works, I want to be sure that ReservationId is unique.  Here is my setup for Reservations Containers.


     When you look at this setup, you might think that ReservationId will be unique in Reservations Container just like a Primary Key on a table in SQL Server. Hold on your seats... This setup does not give you what you might expect. ReservationId will be unique for each RoomNumber not for the whole Reservations container! That means you can make the same ReservationId multiple times in Reservations container. id works just like unique keys; id property is unique for each logical partition. That means you can have the same id multiple times in a container!

     Let's demo this. First, I inserted the following Reservation into this container.


     Next, I will insert the same Reservation with different Room Number. 

I was able to use the same ReservationId in the same container! It looks like Unique Key might not be that unique in Cosmos DB. Let's try to insert another Reservation with the same ReservationId but this time I will use the same RoomNumber too. As you can see in the following document, I am passing a different id so Cosmos DB will not throw error for same id.

This time, I get a Conflict error from CosmosDB.

     Unique Keys are unique for each logical partition not the whole Container. Also, id property works just like unique keys and its values are unique for each logical partition.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thanks your post; it saved me time and effort to understand the difference between custom unique key and system unique key (item id).

    ReplyDelete