Cosmos DB:如何在创建文档时将分区键的值设置为 id?

Cosmos DB: How to set the value of partition key to id when create a document?

我想创建这样的容器:

https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-model-partition-example#posts-container

{
    "id": "<post-id>",
    "type": "post",
    "postId": "<post-id>",
    "userId": "<post-author-id>",
    "title": "<post-title>",
    "content": "<post-content>",
    "creationDate": "<post-creation-date>"
}
...

postId 是这个容器的分区键,我必须将它的值设置为 id.

如何操作?

  1. 我创建了一个post.
  2. Cosmos DB 设置其 id
  3. 我将其 postId 设置为 id <- 如何设置?

我认为从那个页面的想法是你将拥有相同的实体,这样你就可以更容易地查询你的宇宙。

因此,就如何设置 id 而言,它很简单,您需要自己设置它

document.Id = "post-id";
document.PostId = "post-id";

另一方面,如果您使用的是 .net,那么您可以做什么

public class Document
    {
        
        public string Id { get; set; }
        public string Type { get; set; }
        public string PostId { get; set; }

        public static Document CreatePost(string postId)
        {
            return new Document()
            {
                Id = postId,
                PostId = postId,
                Type = "post"
            };
        }

        public static Document CreateComment(string postId, string commentId)
        {
            return new Document()
            {
                Id = commentId,
                PostId = postId,
                Type = "comment"
            };
        }
    }

那么在你的代码中你会做

var post = Document.CreatePost(Guid.NewGuid().ToString())