Azure Cosmos DB-删除文档

Azure Cosmos DB-删除文档,azure,azure-cosmosdb,Azure,Azure Cosmosdb,如何从Cosmos数据库中删除单个记录 我可以使用SQL语法选择: SELECT * FROM collection1 WHERE (collection1._ts > 0) 确实,所有类似于行的文档?归还 但是,当我尝试删除时,这不起作用 DELETE FROM collection1 WHERE (collection1._ts > 0) 如何实现这一点?DocumentDB API的SQL专门用于查询。也就是说,它只提供选择,不提供更新或删除 这些操作完全受支持,但需要RE

如何从Cosmos数据库中删除单个记录

我可以使用SQL语法选择:

SELECT *
FROM collection1
WHERE (collection1._ts > 0)
确实,所有类似于行的文档?归还

但是,当我尝试删除时,这不起作用

DELETE
FROM collection1
WHERE (collection1._ts > 0)

如何实现这一点?

DocumentDB API的SQL专门用于查询。也就是说,它只提供选择,不提供更新或删除

这些操作完全受支持,但需要REST或SDK调用。例如,对于.net,您可以调用DeleteDocumentSync或ReplaceDocumentSync,而在node.js中,这将是对deleteDocument或replaceDocument的调用


在您的特定场景中,您可以运行您的SELECT来标识删除文档,然后删除DELETE,每个文档一个,或者为了效率和事务性,将一个文档的数组传递到一个存储过程。

< P>另一个要考虑的选项是TTL的生存时间。您可以为集合启用此选项,然后为文档设置过期时间。文档过期时将自动为您清理。

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

/**
 * 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和一个选择文档的查询示例:从c中选择c.\u self以删除所有文档


基于

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


下面是一个如何使用.net Cosmos的示例

由于执行边界,必须使用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;
    }

啊,好吧,又一个谜题出现了。我正在使用Python,可以看到DeleteDocument。谢谢对于SDK的java版本,这可能吗?@blackuprise-是的,java完全支持这一点。您将找到DocumentClient的deleteDocument方法。@DavidMakogon在没有分区键的情况下可以使用deleteDocument吗?我正在使用存储过程,但它不起作用。迄今为止,我找到的最简单的解决方案对我不起作用。设置TTL至1秒后。文档不可见,但在返回TTL关闭后,文档再次出现。@DOminikMinc您可能需要再等一会儿。云删除项目需要一些时间。@marc_s我是否需要使用相同的查询格式,例如从c中选择c._self,或者我是否可以从c中选择*。另外,分区键是分区键的名称吗?现在尝试几个小时。如果我从Azure门户调用它,效果非常好,并且从客户端C应用调用它时不会失败。但从不删除任何记录。我做错了什么?为什么我不能从我的客户端应用程序中删除记录?包括c客户端代码在内的任何示例?无法使用此选项删除任何记录。返回0个已删除的文档。
public class BulkDeleteResponse
{
    [JsonProperty("deleted")]
    public int Deleted { get; set; }

    [JsonProperty("continuation")]
    public bool Continuation { get; set; }
}