![](/img/trans.png)
[英]Azure Cosmos DB - difference in how the partition key is supplied to query?
[英]How to delete object from Cosmos DB without knowing the partition key value?
如果我沒有分區鍵值,如何刪除文檔?
我有文檔的id
和分區鍵的屬性名稱(在我的例子中: type
)。
我試過:
var docLink = UriFactory.CreateDocumentUri(databaseName, collectionName, documentId);
var resp = client.DeleteDocumentAsync(docLink).Result;
出現錯誤: PartitionKey value must be supplied for this operation.
示例文檔:
{
"id": "AB12CD",
"type": "Company",
"Address": "123 Test Street"
}
我試圖獲取特定文檔 ID 的分區鍵值
使用 C# 代碼...
我嘗試通過其id
讀取文檔,然后提取type
值,但出現錯誤: InvalidOperationException: PartitionKey value must be supplied for this operation.
用於使用以下代碼。
var response = client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, id)).Result;
我還嘗試了跨分區查詢:
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
^ 返回一個空列表。 如果我檢查 Azure 門戶,我可以看到數據庫中確實存在具有該特定 ID 的文檔。
只需參考此文檔,您就會找到答案。
在 C# 代碼中,請使用Undefined.Value
一切都會好起來的。
client.DeleteDocumentAsync(
UriFactory.CreateDocumentUri(DbName, CollectionName, id),
new RequestOptions() { PartitionKey = new PartitionKey(Undefined.Value) });
希望對你有幫助。
更新答案:
也許我昨天誤解了你的要求,讓我在這里做一個新的澄清。
首先,您的集合按分區字段進行分區: 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]);
2.如果你知道partition key的值,並且文檔確實有partition字段,請在FeedOptions中傳入partition key屬性。
3.如果您知道文檔在分區集合中沒有分區字段,請使用Undefined.Value
。
如果有人來這里使用 python sdk 來delete_item
。 如果項目沒有定義分區鍵
將空字典傳遞給partition_key
參數以刪除項目。
cosmosContainerClient.delete_item(item['id'], partition_key={})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.