简体   繁体   中英

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

I want to create a container like this:

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 is the partition key of this container and I have to set its value equal to id .

How to do this?

  1. I create a post.
  2. Cosmos DB set its id
  3. I set its postId equal to id <- How?

I think from that page idea is that you will have same entity so you can query your cosmos easier.

So in terms how do you set id its simple you will need to set it yourself

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

On the other hand if you are using lets say .net what you can do

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"
            };
        }
    }

So then in your code you will do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM