插入文档时响应状态码不表示成功

Response status code does not indicate success when inserting documents

我的容器上有以下分区 ID: /船号

我正在尝试添加此对象的集合:

public class CoachVessel
{
    [JsonProperty("id")]
    public string vesselId { get; set; }

    [JsonProperty("imo")]
    public long Imo { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

这是我批量插入文档的代码:

 CosmosClientOptions options = new CosmosClientOptions() { AllowBulkExecution = true };
 CosmosClient cosmosclient = new CosmosClient(connStr, options);
 Container container = cosmosclient.GetContainer("CoachAPI", "Vessels");
    
 List<Task> concurrentTasks = new List<Task>();
 foreach (var vessel in vessels.Take(1))
 {
     concurrentTasks.Add(container.CreateItemAsync(vessel, new PartitionKey(vessel.vesselId)));
 }        
 await Task.WhenAll(concurrentTasks);

我收到以下未提供太多信息的错误?

Microsoft.Azure.Cosmos.CosmosException: 'Response status code does not indicate success: BadRequest (400); Substatus: 1001; ActivityId: ; Reason: ();'

有什么原因导致的吗?这是我的设置:

我在删除文档时遇到同样的问题:

CosmosClientOptions options = new CosmosClientOptions() { AllowBulkExecution = true,  MaxRetryAttemptsOnRateLimitedRequests=1000};
CosmosClient cosmosclient = new CosmosClient(connStr, options);
Container container = cosmosclient.GetContainer("CoachAPI", "Vessels");


var allItemsQuery = container.GetItemQueryIterator<string>("SELECT * FROM c.id");

List<Task> concurrentDeleteTasks = new List<Task>();

while (allItemsQuery.HasMoreResults)
{
    foreach (var item in await allItemsQuery.ReadNextAsync())
    {
        concurrentDeleteTasks.Add(container.DeleteItemAsync<string>(item, new PartitionKey("id")));
    }
}
            
await Task.WhenAll(concurrentDeleteTasks.Take(3));

抛出以下错误: '响应状态码不表示成功:NotFound(404);子状态:0;

我来自 CosmosDB 工程团队。根据您的问题,您已将容器上的分区键定义为 /vesselId,而文档已将 vesselId 映射到 CoachVessel class 中的“id”属性。这是故意的吗?

如果在 CreateItemAsync API 中指定了可选的 PartitionKey,则它需要与 Document 中的分区键匹配。如果您打算将“id”作为分区键,则需要将容器的分区键定义为“id”,而不是“vesselId”。在这种情况下,如果容器的分区键确实是 /vesselId,则代码期望输入文档中的 属性“vesselId”设置为分区键中指定的值 vessel.vesselId。您的输入文档中似乎缺少“vesselId”属性。

分区键必须与文档正文中的 属性 匹配。将容器的分区键更改为 /id 并修复删除代码以正确指定分区键。例如,

concurrentDeleteTasks.Add(container.DeleteItemAsync<string>(item, new PartitionKey(item.Id)));

在我的例子中,出现以下错误是因为我将 .Net SDK 从 v2 更新到 v3,如果没有通过,它不再自动生成 ID。

Microsoft.Azure.Cosmos.CosmosException: 'Response status code does not indicate success: BadRequest (400); Substatus: 1001; ActivityId: ; Reason: ();'

我使用存储库模式,所以在调用 CreateItemAsync 之前添加了一个检查:

if (item.Id == null)
{
    item.Id = Guid.NewGuid().ToString();
}