CosmosDB创建独特的文档

问题描述 投票:0回答:1

目前,我在C#中使用带有SQL API的CosmosDB。现在,当它在Event集合中创建一个新事件时,它需要在EventData集合中创建一个具有相同id,eventid和origin的文档。然后它需要将计数设置为1.如果文档已存在于事件集合中,则会抛出一个错误,即eventid是唯一的,它需要更新EventData中的相应计数。我将分区键设置为/ origin,将唯一键设置为/ eventid。这就是我想出来的但是没有得到我需要的任何东西我尝试:

进入活动的数据:

{
    "id": randomly generated from cosmosdb,
    "eventid": "1234",
    "origin": "5.6.7.8"
}

在EventData中需要做什么:

{
    "id": same as the id from the Event collection,
    "eventid": "1234",
    "origin": "5.6.7.8",
    "count": 1
}

然后当一个事件进来并且事件ID为“1234”时,它会发现它已经在Event集合中并在EventData中递增相应的文档:

{
    "id": same as the id from the Event collection,
    "eventid": "1234",
    "origin": "5.6.7.8",
    "count": 2
}

Azure功能:

public static async Task CreateEventAndUpdateCountAsync(string database, string eventCollection, string eventDataCollection, string input){
    MyClass myClass = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(input);
    try
    {
        //try to create a document, if not catch error
        //create document in Event collection, and if no error create a document with the count of 1

        await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(database, eventCollection), myClass, new RequestOptions { PartitionKey = new PartitionKey(myClass.origin) });
        Count count = new Count();
        count.eventid = myClass.eventid;
        count.origin = myClass.origin;
        await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(database, eventDataCollection), count, new RequestOptions { PartitionKey = new PartitionKey(myClass.origin) });
    }
    catch (DocumentClientException de)
    {
        if (de.StatusCode == HttpStatusCode.Conflict)
        {
            // had it trying to read the document and do a ReplaceDocumentAsync
            // need to find the document in the EventData Collection with the same eventid as myClass and increase count by 1               
        }


        else
        {
            log.Info(de.ToString());
            throw;
        }        

    }
}

public class myClass {
    public string eventid { get; set; }
    public string origin { get; set; }
}

public class Count {
    public string eventid { get; set; }
    public string origin { get; set; }
    public int count { get; set; } = 1;
}

谢谢

azure azure-cosmosdb
1个回答
0
投票

CosmosDB SDK支持Upsert方法。如果缺少某些内容,此方法将创建,如果存在则更新。

你可以改变你的第二个CreateDocumentAsync电话:

await client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(database, eventDataCollection), count, new RequestOptions { PartitionKey = new PartitionKey(myClass.origin) });

© www.soinside.com 2019 - 2024. All rights reserved.