如何在不知道分区键值的情况下从 Cosmos DB 中删除对象?

era*_*rad 6 c# azure-cosmosdb

如果我没有分区键值,如何删除文档?

我有id文档和分区键的属性名称(在我的例子中:)type

我试过:

var docLink = UriFactory.CreateDocumentUri(databaseName, collectionName, documentId);
var resp = client.DeleteDocumentAsync(docLink).Result;
Run Code Online (Sandbox Code Playgroud)

有错误: PartitionKey value must be supplied for this operation.

示例文档:

{
   "id": "AB12CD", 
   "type": "Company", 
   "Address": "123 Test Street"
}
Run Code Online (Sandbox Code Playgroud)

我试图获取特定文档 ID 的分区键值

使用 C# 代码...

我试图通过它读取文档id,然后提取该type值,但出现错误:InvalidOperationException: PartitionKey value must be supplied for this operation.使用以下代码。

var response = client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, id)).Result;
Run Code Online (Sandbox Code Playgroud)

我还尝试了跨分区查询:

FeedOptions queryOptions = new FeedOptions { MaxItemCount = 10 };
queryOptions.EnableCrossPartitionQuery = true;
var queryString =  "SELECT * FROM c WHERE c.id= '" + id + "'";
var QueryInSql = client.CreateDocumentQuery<JObject>(
                documentCollectionUri,,
                queryOptions).AsDocumentQuery();
var result = QueryInSql.ExecuteNextAsync<JObject>().Result;

res = result.ToList<JObject>(); //if result has nothing, will be empty list
Run Code Online (Sandbox Code Playgroud)

^ 返回一个空列表。如果我检查 Azure 门户,我可以看到数据库中确实存在具有该特定 ID 的文档。

Jay*_*ong 11

只需参考此文档,您就会找到答案。

在 C# 代码中,请使用Undefined.Value,一切都会好起来的。

client.DeleteDocumentAsync(
          UriFactory.CreateDocumentUri(DbName, CollectionName, id), 
          new RequestOptions() { PartitionKey = new PartitionKey(Undefined.Value) });
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助。


更新答案:

也许我昨​​天误解了你的要求,让我在这里做一个新的澄清。

首先,您的集合按分区字段进行分区:type

1.如果您不知道分区键的值并且文档确实有分区字段,请使用EnableCrossPartitionQuery属性。

FeedOptions queryOptions = new FeedOptions
        {
            MaxItemCount = 10,
            EnableCrossPartitionQuery = true
        };
 var id = '1';
 var queryString = "SELECT * FROM c WHERE c.id= '" + id + "'";
 var QueryInSql = client.CreateDocumentQuery<JObject>(
                        uri,
                        queryString,
                        queryOptions).AsDocumentQuery();
 var result = QueryInSql.ExecuteNextAsync<JObject>().Result;

 var res = result.ToList<JObject>(); //if result has nothing, will be empty list


 Console.WriteLine("\nRead {0}", res[0]);
Run Code Online (Sandbox Code Playgroud)

2.如果你知道partition key的值,并且文档确实有partition字段,请在FeedOptions中传入partition key属性。

3.如果您知道文档在分区集合中没有分区字段,请使用Undefined.Value.


Moh*_*diq 5

万一有人来这里delete_item使用 python sdk。如果该项目没有定义分区键

将空字典传递给partition_key参数以删除该项目。

cosmosContainerClient.delete_item(item['id'], partition_key={})
Run Code Online (Sandbox Code Playgroud)