首页 > 解决方案 > Cosmos DB - 使用 Python 删除所有数据的问题

问题描述

我正在使用来自 azure 的 Cosmos db 和使用 python 的 SQL API。

我已经将一些数据上传到 cosmos db,但现在我想删除它。

我在这个问题中看到了如何做到这一点:Cosmos DB - Delete Document with Python

但对我来说不起作用,这是我的代码:

config = {
    'ENDPOINT': "ENDPOINT",
    'MASTERKEY': 'key',
    'DOCUMENTDB_DATABASE': 'database',
    'DOCUMENTDB_COLLECTION': 'collection'
};

# Initialize the Python DocumentDB client
client = document_client.DocumentClient(config['ENDPOINT'], {'masterKey': config['MASTERKEY']})

# use a SQL based query to get a bunch of documents
query = { 'query': 'SELECT * FROM c' }

options = {}
options['enableCrossPartitionQuery'] = True
options['maxItemCount'] = -1
options['partitionKey'] = '2017'

result_iterable = client.QueryDocuments('dbs/database/colls/collection', query, options)

results = list(result_iterable);

print(results)

#client.DeleteDocument('dbs/ToDoList/colls/nc4data/docs/'+result_iterableID,options)
for x in range(0, len (results)):
    docID = results[x]['id']
    print (docID)
    client.DeleteDocument('dbs/database/colls/collection/docs/'+docID, options=options)
    print ('deleted', docID)
#print ('delete success')

我的分区键是年,从 2016 年到 2019 年。我尝试将选项中的分区键作为年份之一,正如我在上面链接的答案:

options['partitionKey'] = '2017'

我也试过这样做:

options['partitionKey'] = 2017 (year is string, but I was trying)
options['partitionKey'] = 'year'
options['partitionKey'] = '/year'

当我在我的选项字典中插入这个“partitionKey”时,我在结果中获得了一个空列表。

我也试过没有这个'partitionKey',然后我得到所有数据,但我得到这个错误:

{\"Errors\":[\"x-ms-partitionkey 标头中提供的分区键的组件少于集合中定义的组件。

标签: pythonazure-cosmosdb

解决方案


我在上一个线程中测试了代码:Cosmos DB - 使用 Python 删除文档,它工作正常。

import pydocumentdb;
import pydocumentdb.document_client as document_client

config = {
    'ENDPOINT': 'Your url',
    'MASTERKEY': 'Your master key',
    'DOCUMENTDB_DATABASE': 'familydb',
    'DOCUMENTDB_COLLECTION': 'familycoll'
};

# Initialize the Python DocumentDB client
client = document_client.DocumentClient(config['ENDPOINT'], {'masterKey': config['MASTERKEY']})

# use a SQL based query to get a bunch of documents
query = { 'query': 'SELECT * FROM server s' }

options = {}
options['enableCrossPartitionQuery'] = True
options['maxItemCount'] = 2

result_iterable = client.QueryDocuments('dbs/familydb/colls/familycoll', query, options)

results = list(result_iterable);

print(results)

client.DeleteDocument('dbs/familydb/colls/familycoll/docs/id1',options)

print 'delete success'

我从github搜索了确切的问题,我发现它是由sdk版本引起的。您可以升级您的软件包版本或通过 Fiddler Tool 监控 https 请求。请参考以下线程:

1. https://github.com/Azure/azure-sdk-for-ios/issues/108

2. https://github.com/Azure/azure-sdk-for-android/issues/75

3. https://github.com/Azure/azure-sdk-for-ios/pull/114


推荐阅读