python - 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 标头中提供的分区键的组件少于集合中定义的组件。
解决方案
我在上一个线程中测试了代码: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
推荐阅读
- python - MySQL游标使用最后一个游标更新所有列
- android - 为什么 contentResolver.query() 返回 null?
- vue.js - 无法使用 JsPdf 导出 pdf
- python - 如何使用 argparse 以 xml 格式传递参数?
- python - 将 $45,000,000.00 (str) 转换为浮点数
- react-redux - 无法访问组件中的 redux 状态
- java - 带有 lambda 的原子变量
- r - 根据组对值进行排序
- microsoft-dynamics - Dynamics Nav - 如何检测用户取消选择行
- excel - 使用 VBA 更新切片器(OLAP 数据馈送)