Cosmos DB - 删除文档

时间:2017-10-22 08:15:06

标签: azure azure-cosmosdb

如何从Cosmos DB中删除单个记录?

我可以选择使用SQL语法:

SELECT *
FROM collection1
WHERE (collection1._ts > 0)

确实返回所有文件(类似于行?)

但是,当我尝试删除

时,这不起作用
DELETE
FROM collection1
WHERE (collection1._ts > 0)

我如何实现这一目标?

5 个答案:

答案 0 :(得分:21)

DocumentDB API的SQL专门用于查询。也就是说,它只提供SELECT,而不是UPDATEDELETE

完全支持这些操作,但需要REST(或SDK)调用。例如,使用.net,您可以拨打DeleteDocumentAsync()ReplaceDocumentAsync(),在node.js中,这可以是对deleteDocument()replaceDocument()的调用。

在您的特定方案中,您可以运行SELECT来识别要删除的文档,然后进行“删除”调用,每个文档一个(或者,为了提高效率和事务性,将一系列文档传递给删除,进入存储过程。)

答案 1 :(得分:5)

最简单的方法可能是使用Azure Storage Explorer。连接后,您可以深入到所选的容器,选择一个文档,然后将其删除。您可以在https://gotcosmos.com/tools上找到Cosmos DB的其他工具。

Use Azure Storage Explorer to connect to Cosmos DB

答案 2 :(得分:4)

另一个需要考虑的选择是生存时间(TTL)。您可以为集合启用此选项,然后为文档设置到期日期。文件将在您过期时自动清理。

答案 3 :(得分:2)

使用以下代码创建存储过程:

/**
 * 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();
        }
    }
}

并使用分区键(例如:null)和查询来执行选择文档的操作(例如:SELECT c._self FROM c以删除所有文件)。

基于Delete Documents from CosmosDB based on condition through Query Explorer

答案 4 :(得分:0)

以下是如何通过 .net Cosmos bulkDeleteStoredProcedure 使用 SDK V3 的示例。

由于执行边界,必须使用 ContinuationFlag。

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; }
}