1

我有两个系列。据我所知(如果我错了,请随时纠正我),那么您无法在集合之间加入数据。所以我正在寻找更新一个集合的最佳方法,每次将文档添加到另一个集合时。让我们举一个简单的例子:

船只:

[
    {
        "name": "vessel1",
        "id":1,
        "latestReportId":null,
        "latestReportName":null
    },
    {
        "name": "vessel2",
        "id":2,
        "latestReportId":null,
        "latestReportName":null
    }
]

报告:报告

[
    {
        "name": "Report1",
        "id":1
    },
    {
        "name": "Report1",
        "id":1
    }
]

我的第一个想法是使用触发器,但我读到该触发器只能应用于当前分区。这样做的正确方法是什么?我不能是唯一一个想要集合之间关系的人:D

4

1 回答 1

3

您可以使用 Azure Functions 中的Cosmos DB 触发器来同步这两个集合。

触发器可以侦听一个集合中的更改并在另一个集合中执行(更新/插入)数据。

完整的代码示例和说明在本文中,但基本上您可以创建触发器并将其与输出绑定绑定,如下所示:

public static async Task Run([CosmosDBTrigger(
    databaseName: "your-origin-database",
    collectionName: "your-origin-collection",
    ConnectionStringSetting = "your-origin-connectionstringsettings"
    ] IReadOnlyList<Document> documents,
    [CosmosDB("your-destination-database", 
    "your-destination-collection", 
    ConnectionStringSetting = "your-destination-connectionstringsettings")] IAsyncCollector<Document> saveDocuments,
    ILogger log)
{
    foreach (var doc in documents)
    {
        try
        {
            // do any transformation required to the original document
            await saveDocuments.AddAsync(doc); // You could also create a new document here based on information from the first one
        }
        catch(Exception ex)
        {
            log.LogError($"Failed to process document id {doc.Id}: {ex.Message}");
        }
    }
}
于 2018-10-12T13:45:47.540 回答