当我尝试删除Cosmos DB的资源时,出现以下错误:找不到资源。当我开始使用带有分区键的无限制集合时,它开始发生。没有partionkey和限制10GB的收集,这可以正常工作。
protected async Task<bool> DeleteDocument(Resource document)
{
var documentUri = UriFactory.CreateDocumentUri(_db.Options.Value.DatabaseName, _db.Options.Value.CollectionName, document.Id);
ResourceResponse<Document> result = null;
var options = new RequestOptions
{
PartitionKey = new PartitionKey("moachingpartionkey")
};
for (int i = 0; i < MaxRetryCount; i++)
{
try
{
result = await _db.Client.DeleteDocumentAsync(documentUri, options);
break;
}
catch (DocumentClientException dex) when (dex.StatusCode.HasValue && (int)dex.StatusCode.Value == 429)
{
_logger.LogWarning($"");
await Task.Delay(dex.RetryAfter);
}
}
if (result == null)
return false;
int statusCode = (int)result.StatusCode;
return statusCode >= 200 && statusCode < 300;
}
这是我的作品:
protected async Task<bool> CreateDocumentAsync(Resource document)
{
var collectionUri = UriFactory.CreateDocumentCollectionUri(_db.Options.Value.DatabaseName, _db.Options.Value.CollectionName);
ResourceResponse<Document> result = null;
for (int i = 0; i < MaxRetryCount; i++)
{
try
{
result = await _db.Client.CreateDocumentAsync(collectionUri, document);
break;
}
catch (DocumentClientException dex) when (dex.StatusCode.HasValue && (int)dex.StatusCode.Value == 429)
{
_logger.LogWarning($"");
await Task.Delay(dex.RetryAfter);
}
}
if (result == null)
return false;
int statusCode = (int)result.StatusCode;
return statusCode >= 200 && statusCode < 300;
}
答案 0 :(得分:1)
由于您在注释中提出了要求,因此以下是我在创建集合时用于添加分区键的代码:
var collection = new DocumentCollection
{
Id = "Customers", // just an example collection
};
// Set partition key
collection.PartitionKey.Paths.Add("/CountryId"); // just an example of the partition key path
// Set throughput
var options = new RequestOptions
{
OfferThroughput = 400, // Default value is 10000. Currently set to minimum value to keep costs low.
};
// Create
await client.CreateDocumentCollectionIfNotExistsAsync(
UriFactory.CreateDatabaseUri("YourCosomosDatabaseId"),
collection,
options);
这是我用来删除文档的代码。请注意,我首先检查它是否存在,否则会出现异常。
// Check if it exists, otherwise delete throws
var doc = await GetByIdAsync(id, 99); // your method to fetch the document by Id, the partition key (CountryId) is 99
if (doc == null)
{
return true; // Indicates successful deletion
}
// Delete
var uri = UriFactory.CreateDocumentUri("YourCosomosDatabaseId", "Customers", id);
var reqOptions = new RequestOptions { PartitionKey = new PartitionKey(99) }; // CountryId is 99
var result = await Client.DeleteDocumentAsync(uri, reqOptions);
return result.StatusCode == HttpStatusCode.NoContent;
要澄清一些术语-
当您说PartitionKey
时, 表示类似int
或string
之类的值,例如上面的99
。而当您说
PartitionkeyPath
时,则表示该财产 文档中的路径/名称,例如上面的/CountryId
。