Skip to content

Instantly share code, notes, and snippets.

@sjwaight
Last active October 27, 2020 16:17
Show Gist options
  • Save sjwaight/3c5cf9503f588b190b5ff02bb79f07f0 to your computer and use it in GitHub Desktop.
Save sjwaight/3c5cf9503f588b190b5ff02bb79f07f0 to your computer and use it in GitHub Desktop.
How to pass an array of items from Python to a Cosmos DB Stored Procedure (v3 Python SDK or earlier).
import uuid
import os
# v3 Python SDK - note that v4 changed the API and stored procedures now live in the azure.cosmos.scripts module.
import azure.cosmos.documents as documents
import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.errors as errors
COSMOS_HOST = os.environ['COSMOS_HOST']
MASTER_KEY = os.environ['MASTER_KEY']
DATABASE_ID = os.environ['DATABASE_ID']
COLLECTION_ID = os.environ['COLLECTION_ID']
database_link = 'dbs/' + DATABASE_ID
collection_link = database_link + '/colls/' + COLLECTION_ID
# Use sample bulk SP from here: https://github.com/Azure/azure-cosmosdb-js-server/blob/master/samples/stored-procedures/BulkImport.js
sproc_link = collection_link + '/sprocs/bulkImport'
def create_cosmos_entity(jobid, test):
return {
'JobID': jobid,
'Test': test
}
def main():
new_docs = []
counter = 0
while counter < 30:
new_docs.append(create_cosmos_entity(str(uuid.uuid4()), counter))
counter += 1
if(len(new_docs) > 0 and counter < 100):
client = cosmos_client.CosmosClient(COSMOS_HOST, {'masterKey': MASTER_KEY})
# The key here is to include [] around 'new_docs' otherwise call fails!
client.ExecuteStoredProcedure(sproc_link, [new_docs])
@sjwaight
Copy link
Author

Recommend having a read through this Stack Overflow question and the accepted answer: https://stackoverflow.com/questions/48798523/azure-cosmos-db-asking-for-partition-key-for-stored-procedure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment