Working with Azure CosmosDB from Python Part.2

Continuing from the last time, I would like to dig a little deeper into the code. Last proceedings → https://qiita.com/komiyasa/items/ae34fd9fec46c0e01b35

Tutorial code

The following is the whole. In this whole, set the name of the database and the name of the container. It seems that the specific contents are set in another Python file.

Program.py


from azure.cosmos import exceptions, CosmosClient, PartitionKey
import family

# Initialize the Cosmos client
endpoint = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

# <create_cosmos_client>
client = CosmosClient(endpoint, key)
# </create_cosmos_client>

# Create a database
# <create_database_if_not_exists>
database_name = 'AzureSampleFamilyDatabase'
database = client.create_database_if_not_exists(id=database_name)
# </create_database_if_not_exists>

# Create a container
# Using a good partition key improves the performance of database operations.
# <create_container_if_not_exists>
container_name = 'FamilyContainer'
container = database.create_container_if_not_exists(
    id=container_name, 
    partition_key=PartitionKey(path="/lastName"),
    offer_throughput=400
)
# </create_container_if_not_exists>


# Add items to the container
family_items_to_create = [family.get_andersen_family_item(), family.get_johnson_family_item(), family.get_smith_family_item(), family.get_wakefield_family_item()]

 # <create_item>
for family_item in family_items_to_create:
    container.create_item(body=family_item)
# </create_item>

# Read items (key value lookups by partition key and id, aka point reads)
# <read_item>
for family in family_items_to_create:
    item_response = container.read_item(item=family['id'], partition_key=family['lastName'])
    request_charge = container.client_connection.last_response_headers['x-ms-request-charge']
    print('Read item with id {0}. Operation consumed {1} request units'.format(item_response['id'], (request_charge)))
# </read_item>

# Query these items using the SQL query syntax. 
# Specifying the partition key value in the query allows Cosmos DB to retrieve data only from the relevant partitions, which improves performance
# <query_items>
query = "SELECT * FROM c WHERE c.lastName IN ('Wakefield', 'Andersen')"

items = list(container.query_items(
    query=query,
    enable_cross_partition_query=True
))

request_charge = container.client_connection.last_response_headers['x-ms-request-charge']

print('Query returned {0} items. Operation consumed {1} request units'.format(len(items), request_charge))
# </query_items>

Initialization of CosmosClient

client = CosmosClient(endpoint, key)

The endpoint and Key are set here. Set the value to client by getting the Key of the deployed Cosmos DB from the Azure portal.

Create a new database

database_name = 'AzureSampleFamilyDatabase'
database = client.create_database_if_not_exists(id=database_name)

I'm creating a new database, with the condition that if I don't have a name on it. Here we created a database called ʻAzureSampleFamilyDatabase`.

Create a new container

container_name = 'FamilyContainer'
container = database.create_container_if_not_exists(
    id=container_name, 
    partition_key=PartitionKey(path="/lastName"),
    offer_throughput=400
)

Now create a container named FamilyContainer. This is also conditional if not.

Add to container

for family_item in family_items_to_create:
    container.create_item(body=family_item)

Now enter the value of Family_item into the container.

Point reading

for family in family_items_to_create:
    item_response = container.read_item(item=family['id'], partition_key=family['lastName'])
    request_charge = container.client_connection.last_response_headers['x-ms-request-charge']
    print('Read item with id {0}. Operation consumed {1} request units'.format(item_response['id'], (request_charge)))

##Query execution using SQL query syntax
query = "SELECT * FROM c WHERE c.lastName IN ('Wakefield', 'Andersen')"

items = list(container.query_items(
    query=query,
    enable_cross_partition_query=True
))

request_charge = container.client_connection.last_response_headers['x-ms-request-charge']

print('Query returned {0} items. Operation consumed {1} request units'.format(len(items), request_charge))

A little arrangement

The easiest arrangement is to change the database name and container name in this code and see if the changes are reflected in the Azure portal. It's a little, but let's change it like this.

database_name = 'AzureSampleFamilyDatabase2'
database = client.create_database_if_not_exists(id=database_name)

The output result of the command is as follows.

PS C:\Users\komiyasa\Val\sample\azure-cosmos-db-python-getting-started> python .\cosmos_get_started.py
Read item with id Andersen_c23dcf0d-de55-43eb-afbe-e102ebb22dcc. Operation consumed 1 request units
Read item with id Smith_efc4369e-0c4b-4609-8dfc-6799df71f07d. Operation consumed 1 request units
Read item with id Johnson_d84a50c0-ce2e-4b53-a3e9-08104a1a1b7d. Operation consumed 1 request units
Read item with id Wakefield_a667cfc4-a266-4b63-a104-a27e636039e8. Operation consumed 1 request units

If you take a look at the Azure portal, you'll see that you have a database with a new name, with the same content in it. image.png

Impressions

This is a convenient sample code because it is very easy to use and can be deployed intuitively. Next time, I'd like to check the Delete / Update method in SQL using the Azure Python SDK.

Recommended Posts

Working with Azure CosmosDB from Python Part.2
Working with Azure CosmosDB from Python (quick start digging)
Image processing with Python (Part 2)
Studying Python with freeCodeCamp part1
Bordering images with python Part 1
BigQuery-Python was useful when working with BigQuery from Python
Scraping with Selenium + Python Part 1
Working with LibreOffice in Python
Python: Working with Firefox with selenium
Working with sounds in Python
Studying Python with freeCodeCamp part2
Image processing with Python (Part 1)
Solving Sudoku with Python (Part 2)
Image processing with Python (Part 3)
Scraping with Selenium + Python Part 2
With skype, notify with skype from python!
Playing handwritten numbers with python Part 1
Call C from Python with DragonFFI
Using Rstan from Python with PypeR
Working with LibreOffice in Python: import
[Automation with python! ] Part 1: Setting file
Install Python from source with Ansible
Create folders from '01' to '12' with python
Run Aprili from Python with Orange
Use Azure Blob Storage from Python
Call python from nim with Nimpy
Automate simple tasks with Python Part0
[Automation with python! ] Part 2: File operation
Read fbx from python with cinema4d
Working with DICOM images in Python
Excel aggregation with Python pandas Part 1
Trial of voice recognition using Azure with Python (input from microphone)
Efficiently develop Azure Python apps with CI/CD
Collecting information from Twitter with Python (Twitter API)
Receive textual data from mysql with python
Get html from element with Python selenium
Play audio files from Python with interrupts
Create wordcloud from your tweet with python3
Play handwritten numbers with python Part 2 (identify)
Process Pubmed .xml data with python [Part 2]
Try working with binary data in Python
Automate simple tasks with Python Part1 Scraping
Tweet from python with Twitter Developer + Tweepy
Post Test 3 (Working with PosgreSQL in Python)
Business efficiency starting from scratch with Python
Decrypt files encrypted with openssl from python with openssl
Working with OpenStack using the Python SDK
Image acquisition from camera with Python + OpenCV
Excel aggregation with Python pandas Part 2 Variadic
100 Language Processing Knock with Python (Chapter 2, Part 1)
Getting started with Dynamo from Python boto
FM modulation and demodulation with Python Part 2
[Azure] Hit Custom Vision Service with Python
Try calling Python from Ruby with thrift
Scraping from an authenticated site with python
[Part1] Scraping with Python → Organize to csv!
Use C ++ functions from python with pybind11
Use Python and MeCab with Azure Functions
Working with GPS on Raspberry Pi 3 Python
QGIS + Python Part 2
Collecting information from Twitter with Python (Environment construction)