/**
* A Cosmos DB stored procedure that bulk deletes documents for a given query.
* Note: You may need to execute this stored procedure multiple times (depending whether the stored procedure is able to delete every document within the execution timeout limit).
*
* @function
* @param {string} query - A query that provides the documents to be deleted (e.g. "SELECT c._self FROM c WHERE c.founded_year = 2008"). Note: For best performance, reduce the # of properties returned per document in the query to only what's required (e.g. prefer SELECT c._self over SELECT * )
* @returns {Object.<number, boolean>} Returns an object with the two properties:
* deleted - contains a count of documents deleted
* continuation - a boolean whether you should execute the stored procedure again (true if there are more documents to delete; false otherwise).
*/
function bulkDeleteStoredProcedure(query) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var response = getContext().getResponse();
var responseBody = {
deleted: 0,
continuation: true
};
// Validate input.
if (!query) throw new Error("The query is undefined or null.");
tryQueryAndDelete();
// Recursively runs the query w/ support for continuation tokens.
// Calls tryDelete(documents) as soon as the query returns documents.
function tryQueryAndDelete(continuation) {
var requestOptions = {continuation: continuation};
var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, retrievedDocs, responseOptions) {
if (err) throw err;
if (retrievedDocs.length > 0) {
// Begin deleting documents as soon as documents are returned form the query results.
// tryDelete() resumes querying after deleting; no need to page through continuation tokens.
// - this is to prioritize writes over reads given timeout constraints.
tryDelete(retrievedDocs);
} else if (responseOptions.continuation) {
// Else if the query came back empty, but with a continuation token; repeat the query w/ the token.
tryQueryAndDelete(responseOptions.continuation);
} else {
// Else if there are no more documents and no continuation token - we are finished deleting documents.
responseBody.continuation = false;
response.setBody(responseBody);
}
});
// If we hit execution bounds - return continuation: true.
if (!isAccepted) {
response.setBody(responseBody);
}
}
// Recursively deletes documents passed in as an array argument.
// Attempts to query for more on empty array.
function tryDelete(documents) {
if (documents.length > 0) {
// Delete the first document in the array.
var isAccepted = collection.deleteDocument(documents[0]._self, {}, function (err, responseOptions) {
if (err) throw err;
responseBody.deleted++;
documents.shift();
// Delete the next document in the array.
tryDelete(documents);
});
// If we hit execution bounds - return continuation: true.
if (!isAccepted) {
response.setBody(responseBody);
}
} else {
// If the document array is empty, query for more documents.
tryQueryAndDelete();
}
}
}
private async Task<int> ExecuteSpBulkDelete(string query, string partitionKey)
{
var continuationFlag = true;
var totalDeleted = 0;
while (continuationFlag)
{
StoredProcedureExecuteResponse<BulkDeleteResponse> result = await _container.Scripts.ExecuteStoredProcedureAsync<BulkDeleteResponse>(
"spBulkDelete", // your sproc name
new PartitionKey(partitionKey), // pk value
new[] { sql });
var response = result.Resource;
continuationFlag = response.Continuation;
var deleted = response.Deleted;
totalDeleted += deleted;
Console.WriteLine($"Deleted {deleted} documents ({totalDeleted} total, more: {continuationFlag}, used {result.RequestCharge}RUs)");
}
return totalDeleted;
}
响应模型:
public class BulkDeleteResponse
{
[JsonProperty("deleted")]
public int Deleted { get; set; }
[JsonProperty("continuation")]
public bool Continuation { get; set; }
}
6条答案
按热度按时间qjp7pelc1#
DocumentDB API的SQL是专门用于 * 查询 * 的,即只提供
SELECT
,不提供UPDATE
或DELETE
。这些操作完全受支持,但需要REST(或SDK)调用。例如,在.net中,您将调用
DeleteDocumentAsync()
或ReplaceDocumentAsync()
,而在node.js中,这将是对deleteDocument()
或replaceDocument()
的调用。在您的特定场景中,您可以运行
SELECT
来标识要删除的文档,然后进行“delete”调用,每个文档一个(或者,为了提高效率和事务性,将要删除的文档数组传递到存储过程中)。ig9co6j12#
最简单的方法可能是使用Azure Storage Explorer。连接后,您可以向下钻取到所选的容器,选择一个文档,然后删除它。您可以在https://gotcosmos.com/tools上找到Cosmos DB的其他工具。
bq3bfh9z3#
另一个要考虑的选项是生存时间(TTL)。您可以为集合启用此选项,然后为文档设置过期时间。文档过期后将自动清理。
jv4diomz4#
使用以下代码创建存储过程:
并使用您的分区密钥执行它(例如:null)和用于选择文档的查询(例如:从c中选择c._self以全部删除)。
基于Delete Documents from CosmosDB based on condition through Query Explorer
hgncfbus5#
下面是一个如何使用.net Cosmos SDK V3来使用bulkDeleteStoredProcedure的示例。
由于执行界限,必须使用ContinuationFlag。
响应模型:
fsi0uk1n6#
你可以使用C#通过下面的方法从cosmosdb中删除单个文档--你可以对cosmosdb容器示例使用下面的方法。
客户容器.DeleteItemAsync(ID,新分区键(“分区键的任意值”))
T-〉是容器中项目的类型。
id-〉是要删除的项目的guid。(为此您可以先使用select query从cosmsdb中获取项目)
AnyValueofPartitionKey-大多数情况下,我们使用cosmos数据库容器创建分区键,因此在这里您必须为该键提供一个值,例如-我的键是customerCity,因此我提供了“果阿”。