簡體   English   中英

如何區分 Cosmos DB 更改提要中的插入和更新

[英]How to tell the difference between Insert and Update in Cosmos DB change feed

我確實從該資源中獲得了 Cosmos DB 更改提要的代碼示例

我能夠成功編譯並運行代碼。

這是更改提要調用的代碼

    private static async Task<ChangeFeedProcessor> StartChangeFeedProcessorAsync(
        CosmosClient cosmosClient,
        IConfiguration configuration)
    {
        string databaseName = "changefeedsample";// configuration["SourceDatabaseName"];
        string sourceContainerName = "source";// configuration["SourceContainerName"];
        string leaseContainerName = "leases";// configuration["LeasesContainerName"];

        Container leaseContainer = cosmosClient.GetContainer(databaseName, leaseContainerName);
        ChangeFeedProcessor changeFeedProcessor = cosmosClient.GetContainer(databaseName, sourceContainerName)
            .GetChangeFeedProcessorBuilder<ToDoItem>(processorName: "changeFeedSample", onChangesDelegate: HandleChangesAsync)
                .WithInstanceName("consoleHost")
                .WithLeaseContainer(leaseContainer)
                .Build();

        Console.WriteLine("Starting Change Feed Processor...");
        await changeFeedProcessor.StartAsync();
        Console.WriteLine("Change Feed Processor started.");
        return changeFeedProcessor;
    }

這是對更改提要采取的操作的代碼

static async Task HandleChangesAsync(IReadOnlyCollection<ToDoItem> changes, CancellationToken cancellationToken)
        {
            Console.WriteLine("Started handling changes...");
            foreach (ToDoItem item in changes)
            {
                Console.WriteLine($"Detected operation for item with id {item.id}, created at {item.creationTime}.");
                // Simulate some asynchronous operation
                await Task.Delay(10);
            }

            Console.WriteLine("Finished handling changes.");
        }

我確實看到了如何在插入時觸發操作; 但是,有沒有辦法判斷是否對更新采取了行動。 有沒有辦法分辨哪個是哪個,從另一個中分辨出來。 有沒有辦法獲得有關更新/添加數據的更多詳細信息

非常感謝您提前

有沒有辦法分辨哪個是哪個

CosmosDb 更改提要通過向您發送文檔的當前值來工作。 因此,您無法區分插入或編輯。

如果您只需要區分插入和編輯,那么您可以在您的對象中添加一個bool IsEdited字段,並在編輯文檔時將其設置為 true。 這足以執行諸如要處理插入但忽略編輯的匯總/計數表之類的操作。

如果您還需要處理編輯,則需要檢測多個編輯,而不僅僅是第一個。 在這種情況下,您將需要具有文檔 ID 和上次修改時間 ( _ts ) 的第二個容器,並將傳入的_ts與您已經看到的(如果有)進行比較。 您可能需要一個JavaScript 存儲過程來以原子方式進行比較+更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM