【问题标题】:Deleting a document from Cosmos DB - entity with the specified id does not exist in the system从 Cosmos DB 中删除文档 - 系统中不存在具有指定 ID 的实体
【发布时间】:2021-01-16 17:38:08
【问题描述】:

我在尝试从 CosmosDb 删除文档时遇到问题,据我了解,我首先必须加载要删除的文档,然后将 document.SelfLink 传递给以下方法:

DeleteDocumentAsync

但是,当我尝试删除它时,会引发以下错误:

系统中不存在指定id的实体

我知道该文档存在,因为我可以在 document 变量中看到该文档。

以下是我当前的代码设置:

 private static void DeleteDocument()
    {
        var feedOptions = new FeedOptions
        {
            MaxItemCount = -1,
            EnableCrossPartitionQuery = true
        };

        var document = _documentClient
            .CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(_databaseName, _collection), feedOptions)
            .Where(x => x.Id == "ba00d500-de61-411e-b8ef-f749b23cc326")
            .AsEnumerable()
            .SingleOrDefault();

        if (document == null) return; // Document is not null when I check here

        _documentClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(_databaseName, _collection, document.Id), new RequestOptions { PartitionKey = new Microsoft.Azure.Documents.PartitionKey(document.Id) })
            .GetAwaiter()
            .GetResult();
    }

这是 CosmosDb 中的文档:

我也尝试过引用document.SelfLink 而不是使用UriFactory.CreateDocumentUrl,但结果仍然相同。

更新。

似乎在 Undefined.Value 中传递 PartitionKey 似乎有效:

_documentClient.DeleteDocumentAsync(document.SelfLink, new RequestOptions { PartitionKey = new Microsoft.Azure.Documents.PartitionKey(Undefined.Value) })
            .GetAwaiter()
            .GetResult();

我个人觉得很奇怪。

【问题讨论】:

  • 文档有id(小写)但你的Linq谓词有Id(你引用document.Id

标签: c# azure-cosmosdb


【解决方案1】:

我没有看到任何奇怪的东西,只是需要知道分区键并在向服务器发送请求时指定它。 分区键是文档标识的一部分,就像id-field。即使分区键是undefined

当您查询文档时,您通过EnableCrossPartitionQuery = true 明确请求扫描所有分区,这允许您在查询中省略分区键并仍然获得结果。您也应该在那里传递分区键,以节省成本,但它有效。

对于删除,没有跨分区删除,您必须传入分区键。一旦你这样做了,该文档就被找到了,并且可以被删除。很期待。

此外,不,您不必加载文档来删除它,这只是额外的复杂性、成本和往返服务器。您只需要知道要删除的文档的身份(数据库 + 集合 + 分区 + id)。对于 cosmosDB V2 客户端,以下示例:

var documentUri = UriFactory.CreateDocumentUri(databaseName, containerName, documentId);
var options = new RequestOptions() { PartitionKey = new PartitionKey(partition) };

await cosmosClient.DeleteDocumentAsync(documentUri, options).ConfigureAwait(false);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多