如何区分 Cosmos DB 更改源中的插入和更新

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

我确实从这个 resource

中获得了 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.");
        }

我确实知道如何在插入时触发操作;但是,有没有办法判断是否对更新采取了行动。有没有一种方法可以分辨出哪个是哪个,从一个到另一个。有没有办法获取有关 updated/added 数据

的更多详细信息

非常感谢您

Is there a way to tell which is which

CosmosDb 更改源通过向您发送文档的当前值来工作。因此,您无法区分插入或编辑。

如果您只需要区分插入和编辑,那么您可以在您的对象中添加一个bool IsEdited 字段,并在编辑文档时将其设置为true。这对于执行 summary/count table 之类的操作已经足够了,您可以在其中处理插入但忽略编辑。

如果您还需要处理编辑,那么您将需要检测多个编辑,而不仅仅是第一个。在这种情况下,您需要第二个容器,其中包含文档 ID 和上次修改时间 (_ts),并将传入的 _ts 与您已经看到的容器(如果有)进行比较。你可能需要一个 JavaScript stored procedure 来自动比较+更新。