Azure cosmosdb 当用户容器将userId作为分区键时,需要唯一的用户名

Azure cosmosdb 当用户容器将userId作为分区键时,需要唯一的用户名,azure-cosmosdb,azure-cosmosdb-sqlapi,Azure Cosmosdb,Azure Cosmosdb Sqlapi,我以这篇文章为例 使用userId和username以及分区键作为userId的Users容器 { "id": "54c7da13-f4b8-4668-90dc-7c1aa968a73e", "userId": "54c7da13-f4b8-4668-90dc-7c1aa968a73e", "type": "user", "userna

我以这篇文章为例 使用userId和username以及分区键作为userId的Users容器

{
    "id": "54c7da13-f4b8-4668-90dc-7c1aa968a73e",
    "userId": "54c7da13-f4b8-4668-90dc-7c1aa968a73e",
    "type": "user",
    "username": "jeffw"
}
在我的创建用户页面中,我希望在添加新用户之前确保用户名是唯一的。我尝试了预触发器,但发现“不能跨多个逻辑分区运行存储过程或触发器”。如何确保在创建用户时选择了唯一的用户名?我想我可以将分区键更改为username,但是为什么本文使用userId呢


解决方案

请参阅@markbrown的答案

在用户容器和/或用户名上创建唯一密钥:

await database.Database.DefineContainer(name: "Users", partitionKeyPath: "/userId")
                            .WithUniqueKey().Path("/username").Attach()
                            .CreateIfNotExistsAsync();
然后尝试创建一个userId为“unique_username”的新用户以及尝试创建的新用户名:

{
    "id": "06af2937-4677-4d27-a167-5517aa6d0ffd",
    "userId": "unique_username",
    "type": "unique_username",
    "username": "jeffw"
}
wait\u userscocontainer.CreateItemAsync(uniqueUser,new PartitionKey(“unique\u username”)


如果用户名已存在,则返回冲突状态。示例如下

将分区键更改为username不会有帮助,因为您的容器中可以有该值的倍数。一种方法是使用一个新分区,其中为每个用户名存储一个唯一实例,并在容器上使用唯一索引(唯一索引在逻辑分区中是唯一的)

创建一个新的type=“unique\u user”和一个userId=“unique\u user”。然后在他们注册时添加一个新的带有新用户名的该类型的记录。这将为您带来数百万用户,而不会超过20GB的限制。然后,在创建新用户时,使用“unique_user”类型和新用户名的id在容器上进行插入。如果获得201,则使用type=“user”和其他用户数据执行另一次插入


希望有帮助。

您可以设置索引。

需要一个唯一的键约束以及@mark brown的解决方案。由于UserId是分区键,因此每个用户名都会在其自己的逻辑分区中结束,并且只有唯一键约束不会解决问题(因为每个逻辑分区强制使用唯一键)。