簡體   English   中英

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. 我創建一個帖子。
  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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM