Reputation: 5265
I have two collections. As far as I can read (feel free to correct me if I am wrong) then you cannot join data between collections. So I am looking for the best approach to update one collection, every time documents are added to the other one. Lets take a simple sample:
Vessels:
[
{
"name": "vessel1",
"id":1,
"latestReportId":null,
"latestReportName":null
},
{
"name": "vessel2",
"id":2,
"latestReportId":null,
"latestReportName":null
}
]
Reports: Reports
[
{
"name": "Report1",
"id":1
},
{
"name": "Report1",
"id":1
}
]
My first thought was using a trigger, but I read that trigger can only apply on the current partition. What is the right approach to do this? I can't be the only one that want relations between collections :D
Upvotes: 1
Views: 1427
Reputation: 15613
You could use the Cosmos DB Trigger in Azure Functions to sync both collections.
The Trigger can listen for changes in one collection and act (update/insert) data in another.
The full code sample and explanation is in this article, but basically you can create your trigger and tie it with an Output Binding like so:
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}");
}
}
}
Upvotes: 4