首页 > 解决方案 > Cosmos DB:集合存在,但抛出 410 GONE httpstatus 代码

问题描述

我的一些代码在我的应用程序启动时检查集合是否存在。

但是,要检查的代码:

await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, collectionId));

正在抛出带有 410 GONE http 状态代码的 DocumentClientException。

但是,当我使用我的数据浏览器时,我看到我提供的具有 collectionId 的集合确实存在。此外,我在测试中尝试了以下内容:

try
{
    await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, collectionId));
}
catch (DocumentClientException e)
{

    if (e.StatusCode == System.Net.HttpStatusCode.NotFound || e.StatusCode == System.Net.HttpStatusCode.Gone)
    {
        var collection = new DocumentCollection { Id = collectionId, ResourceId = collectionId };
        await client.CreateDocumentCollectionAsync(
            UriFactory.CreateDatabaseUri(DatabaseId),
            collection,
            new RequestOptions { OfferThroughput = 1000 });
    }
    else
    {
        throw;
    }
}

此代码仍会引发带有 410 状态代码的 DocumentClientException。但是,当我尝试创建文档集合时,它失败了Resource with specified id or name already exists

我的搜索不正确吗?我确实手动创建了集合,所以可能 collectionID 不同,但我无法在代码之外设置文档集合 ID 似乎很奇怪。

标签: .netazureazure-cosmosdb

解决方案


我建议使用DocumentCollectionQuery它来检查它是否存在。ReadDocumentCollectionAsync不太一样。

您可以在Cosmosnaut的 CosmosCollectionCreator.cs 中查看它是如何完成的。

只需查询使用

var collection = _documentClient
            .CreateDocumentCollectionQuery(database.SelfLink)
            .ToArray()
            .FirstOrDefault(c => c.Id == collectionName);

然后用

collection = await _documentClient.CreateDocumentCollectionAsync(database.SelfLink, collection, new RequestOptions
        {
            OfferThroughput = collectionThroughput
        });

推荐阅读