当前,我将CosmosDB与C#中的SQL API结合使用。现在,当它在Event集合中创建新事件时,需要在EventData集合中创建一个具有相同ID,EventID和起源的文档。然后,需要将计数设置为1。如果文档已经存在于Event集合中,则会引发错误,指出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
}
天蓝色功能:
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;
}
谢谢
答案 0 :(得分:0)
CosmosDB SDK支持Upsert
方法。如果缺少某些内容,则会创建此方法,如果存在,则会进行更新。
您可以将第二个CreateDocumentAsync
呼叫更改为此:
await client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(database, eventDataCollection), count, new RequestOptions { PartitionKey = new PartitionKey(myClass.origin) });