Cosmos DB-使用Python删除所有数据中的问题

时间:2019-11-21 16:02:30

标签: python azure-cosmosdb

我正在使用Azure的Cosmos db和使用python的SQL API。

我已经将一些数据上传到了波斯菊数据库,但是现在我想将其删除。

我在这个问题中看到了如何做: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'时,我会在结果中获得一个Empy列表。

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

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

1 个答案:

答案 0 :(得分:1)

我在上一个线程Cosmos DB - Delete Document with 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