How to set up a restriction on a specific item, making it unique in Cosmos DB?

Wei, Bella 0 Reputation points
2023-11-13T21:56:09.1166667+00:00

Hi there,

I'm working on a REST API project that uses Java Spring Boot and Cosmos DB. I have multiple collections in this DB. This is the entity for one of the collections. I'd like to make one property unique, so no duplicate values can be inserted into this collection for the country property. For example, only a unique value can be inserted. If we have already inserted Japan, attempting to reinsert Japanwill result in an error.

Currently, I have set up both the partition key and unique key as country . This achieves the goal of preventing duplicate values from being inserted. However, I'm not sure if it's a good practice to set up a collection like this. Any suggestions?

@Id
@GeneratedValue
private String id;

private String country;    // I want to make it unique, No duplicate value can be inserted
private String description;
private String createdBy;
private String updatedBy;

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,701 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Sajeetharan 2,261 Reputation points Microsoft Employee
    2023-11-17T09:50:51.2333333+00:00

    Yes, your approach of having the partition key combined with the unique key guarantees the uniqueness of an item within the scope of the container.'

    Read more here

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.