0

我确实从该资源中获得了 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.");
        }

我确实看到了如何在插入时触发该操作;但是,有没有办法判断是否对更新采取了行动。有没有办法分辨哪个是哪个,从另一个中分辨出来。有没有办法获得有关更新/添加数据的更多详细信息

非常感谢您提前

4

1 回答 1

2

有没有办法分辨哪个是哪个

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

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

如果您还需要处理编辑,那么您需要检测多个编辑,而不仅仅是第一个。在这种情况下,您需要第二个包含文档 ID 和上次修改时间 ( _ts) 的容器,并将传入_ts的内容与您已经看到的内容(如果有的话)进行比较。您可能需要一个JavaScript 存储过程来以原子方式进行比较+更新。

于 2021-07-16T13:02:06.347 回答