在Azure Cosmos Db中没有分区键的批量删除

时间:2020-03-11 14:16:31

标签: azure stored-procedures azure-cosmosdb

我正在尝试使用存储过程进行批量删除。创建集合时,我没有传递分区密钥。我想删除而没有分区键。 现在,我的查询正在运行,但没有从集合中删除任何内容。是否需要使用分区键进行批量删除/更新?

下面是我的代码:

def delete_bulk(query,client,coll_link):
    sproc = {
                'id': 'deleteProcedure',
                'body': ('''
                    function bulkDeleteProcedure(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], {}, 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();
        }
    }
}
                    ''')
            }

    try:
        # Create a container
        created_sproc = client.CreateStoredProcedure(coll_link, sproc)
        proc_link = created_sproc['_self']
    except Exception as e:
        proc_id = sproc['id']
        proc_query = "select * from r where r.id = '{0}'".format(proc_id)
        proc = list(client.QueryStoredProcedures(coll_link, proc_query))[0]
        proc_link = proc['_self'] 

    client.ExecuteStoredProcedure(proc_link, query)
    print('Deletion Done!!!')

1 个答案:

答案 0 :(得分:2)

我注意到您使用了github code中的批量删除js。该代码运行良好,但是您需要了解一个关键点。

分区密钥应始终随SP一起执行。(请参阅此详细情况:Delete Documents from Cosmos using Query without Partition Key Specification

因此,遵循该语句,存储过程最适合于繁重的写操作,不繁重的读取或删除操作。您可以按照官方建议来了解Bulk Executor Lib SDK。我在此源代码中发现了BulkDelete功能,请尝试一下。