適用於 Python 的 Azure Cosmos DB 程式庫Azure Cosmos DB libraries for Python

概觀Overview

在 Python 應用程式中使用 Azure Cosmos DB 來儲存和查詢 NoSQL 資料存放區中的 JSON 文件。Use Azure Cosmos DB in your Python applications to store and query JSON documents in a NoSQL data store.

深入了解 Azure Cosmos DBLearn more about Azure Cosmos DB.

用戶端程式庫Client library

pip install pydocumentdb

管理程式庫Management library

pip install azure-mgmt-cosmosdb

範例Example

使用類似 SQL 的查詢介面在 Azure CosmosDB 中尋找相符的文件:Find matching documents in Azure CosmosDB using a SQL-like query interface:

import pydocumentdb
import pydocumentdb.document_client as document_client

# Initialize the Python Azure Cosmos DB client
client = document_client.DocumentClient(config['ENDPOINT'], {'masterKey': config['MASTERKEY']})
# Create a database
db = client.CreateDatabase({ 'id': config['DOCUMENTDB_DATABASE'] })

# Create collection options
options = {
    'offerEnableRUPerMinuteThroughput': True,
    'offerVersion': "V2",
    'offerThroughput': 400
}

# Create a collection
collection = client.CreateCollection(db['_self'], { 'id': config['DOCUMENTDB_COLLECTION'] }, options)

# Create some documents
document1 = client.CreateDocument(collection['_self'],
    { 
        'id': 'server1',
        'Web Site': 0,
        'Cloud Service': 0,
        'Virtual Machine': 0,
        'name': 'some' 
    })

# Query them in SQL
query = { 'query': 'SELECT * FROM server s' }    

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

result_iterable = client.QueryDocuments(collection['_self'], query, options)
results = list(result_iterable)

print(results)

範例Samples