Azure Cosmos DB : Unique index constraint violation using UpsertDocumentAsync

标签 azure azure-cosmosdb upsert documentclient

我已在 Azure Cosmos DB 容器中为字段 UniqueName 定义了 UniqueKey 策略。

下面的函数正在计时器上调用。

我正在尝试使用 Azure Functions 绑定(bind)更新 Azure Cosmos DB 中的文档,如下所示:

public async Task ManageItems([ActivityTrigger] string records,
        [CosmosDB(
        databaseName: "mydatabase",
        collectionName: "items",
        ConnectionStringSetting = "CosmosDbConnectionString")] DocumentClient client,
        ILogger log)
        {
             var collectionUri = UriFactory.CreateDocumentCollectionUri("mydatabase", "items");


            
            foreach (var record in records)
            {
                log.LogDebug($"Upserting itemNumber={record.UniqueName}");
                await client.UpsertDocumentAsync(collectionUri, record);
            }
         }

在空白“items”容器中首次执行期间,每条记录的更新插入效果非常好,将每条记录作为特定文档插入。

但是,当对与第一次执行相同的数据进行测试时,但现在期望“更新”而不是“插入”尝试,我得到一个异常:

UpsertDocumentAsync 之后

违反唯一索引约束方法运行。

我在这里缺少什么?

据我了解,Upsert 是更新或插入,具体取决于对象是否存在(通过其唯一标识符)。

检查方法中的传出对象唯一 ID 是否与现有文档唯一 ID 匹配应该在 Cosmos DB 容器级别进行。

我期望发生的是调用注意到具有该唯一 ID 的文档已经存在,并且它执行更新,而不是抛出异常。如果该方法仅插入,我希望它会抛出异常。

最佳答案

此问题已通过在“记录”来源的类中指定显式“id” 字段得到解决。

“id” 已设置为我想用作唯一值的唯一“recordNumber”。

为了更好地衡量,我在 UpsertDocumentAsync 方法中将disableAutomaticIdGeneration 设置为 true

UpsertDocumentAsync(collectionUri, record, disableAutomaticIdGeneration:true);

不再有唯一索引违规,也没有重复。

值得注意的是,该解决方案与此类似:How can I insert/update data in CosmosDB in an Azure function

关于Azure Cosmos DB : Unique index constraint violation using UpsertDocumentAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70162287/

相关文章:

azure - 如何减少保留的RU以降低DocumentDB的成本

azure - 宇宙数据库 : Dynamic Input and Output in Stored Procedure

sql - 如何在 MySQL 中更新(如果存在),如果不存在(又名 "upsert"或 "merge")?

c# - 让 IIS 托管 WCF 服务中的流式传输正常工作

javascript - 在没有 try/catch 的情况下检查 CosmosDB 项目是否存在

sql - Postgres - 关于冲突 - 如何知道是否发生了更新而不是插入

sqlite - 如果不存在则插入其他更新?

azure - SQL Azure 数据仓库 - 当数据库名称包含连字符时如何在 SQL 中扩展

c# - 你调用的对象是空的。使用 TPM 设备客户端发送消息时

sql - Azure blob 到 Azure SQL 数据库 : Cannot bulk load because the file "xxxx.csv" could not be opened. 操作系统错误代码 5(访问被拒绝。)