適用於:
NoSQL
本教學課程會逐步解說如何使用 Visual Studio Code Jupyter 筆記本與 Azure Cosmos DB for NoSQL 帳戶互動。 您將了解如何連線至您的帳戶、匯入資料及執行查詢。
必要條件
建立新的 Notebook
在本節中,您將建立 Azure Cosmos 資料庫、容器,並將零售資料匯入至容器。
- 打開 Visual Studio Code。
- 從命令選擇區 (Ctrl+Shift+P) 執行 Create: New Jupyter Notebook (建立:新增 Jupyter Notebook) 命令,或在工作區中建立新的 .ipynb 檔案。
打開 Visual Studio Code。
從命令選擇區 (Ctrl+Shift+P) 執行 Polyglot Notebook: Create new blank notebook (Polyglot Notebook:建立新的空白筆記本) 命令。
選取 .ipynb 附檔名。
選取 C# 作為預設語言。
提示
現在,新筆記本已建立完成,您可以儲存筆記本並將其重新命名為 AnalyzeRetailData.ipynb 之類的名稱。
使用 SDK 建立資料庫和容器
從預設的程式碼資料格開始。
安裝 Azure.cosmos 套件。 繼續之前,請先執行此資料格。
%pip install azure.cosmos
匯入本教學課程所需的任何套件。
import azure.cosmos
from azure.cosmos.partition_key import PartitionKey
from azure.cosmos import CosmosClient
建立 CosmosClient 的新執行個體。
endpoint = "<FILL ME>"
key = "<FILL ME>"
cosmos_client = CosmosClient(url=endpoint, credential=key)
使用內建 SDK 建立名為 RetailIngest 的資料庫。
database = cosmos_client.create_database_if_not_exists('RetailIngest')
建立名為 WebsiteMetrics 的容器及 /CartID 分割區索引鍵。
container = database.create_container_if_not_exists(id='WebsiteMetrics', partition_key=PartitionKey(path='/CartID'))
選取 [執行] 以建立資料庫和容器資源。
從預設的程式碼資料格開始。
安裝 Microsoft.Azure.Cosmos NuGet 套件。 繼續之前,請先執行此資料格。
#r "nuget: Microsoft.Azure.Cosmos"
建立新的程式碼資料格。
匯入本教學課程所需的任何套件。
using Microsoft.Azure.Cosmos;
使用內建 SDK 建立用戶端類型的新執行個體。 填入 Azure Cosmos DB 帳戶的 URI 端點和金鑰。 您可以在 Azure Cosmos DB 帳戶的金鑰頁面中找到這些值。
var endpoint = "<FILL ME>";
var key = "<FILL ME>";
var cosmosClient = new CosmosClient(Cosmos.Endpoint, Cosmos.Key);
建立名為 RetailIngest 的資料庫。
Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync("RetailIngest");
建立名為 WebsiteMetrics 的容器及 /CartID 分割區索引鍵。
Container container = await database.CreateContainerIfNotExistsAsync("WebsiteMetrics", "/CartID");
選取[執行資料格]以建立資料庫和容器資源。
將資料匯入容器
新增程式碼資料格
在程式碼資料格內,新增下列程式碼以從此 URL 上傳資料:<https://cosmosnotebooksdata.blob.core.windows.net/notebookdata/websiteData.json>。
import urllib.request
import json
with urllib.request.urlopen("https://cosmosnotebooksdata.blob.core.windows.net/notebookdata/websiteData.json") as url:
docs = json.loads(url.read().decode())
for doc in docs:
container.upsert_item(doc)
執行資料格。 此執行時間需要 45 秒到 1 分鐘。
新增程式碼資料格。
在程式碼資料格中,建立新的 C# 類別來代表容器中的項目。 執行資料格。
public class Record
{
public string id { get; set; }
public int CartID { get; set; }
public string Action { get; set; }
public decimal Price { get; set; }
public string Country { get; set; }
public string Item { get; set; }
}
新增程式碼資料格。
在程式碼資料格內,新增下列程式碼以從此 URL 上傳資料:<https://cosmosnotebooksdata.blob.core.windows.net/notebookdata/websiteData.json>。
using System.Net.Http;
using System.Text.Json;
using System.IO;
var dataURL = "https://cosmosnotebooksdata.blob.core.windows.net/notebookdata/websiteData.json";
var jsonData = new HttpClient().GetStringAsync(dataURL).Result;
Record[] result = JsonSerializer.Deserialize<Record[]>(jsonData);
foreach (Record record in result) {
await container.UpsertItemAsync<Record>(record, new PartitionKey(record.CartID)); //43 seconds
}
執行資料格。 此執行時間需要 45 秒到 1 分鐘。
分析您的資料
建立另一個新的程式碼資料格。
在程式碼資料格中,使用 SQL 查詢填入 Pandas DataFrame。 執行此資料格。
import pandas as pd
from pandas import DataFrame
QUERY = "SELECT c.Action, c.Price as ItemRevenue, c.Country, c.Item FROM c"
results = container.query_items(
query=QUERY, enable_cross_partition_query=True
)
df_cosmos = pd.DataFrame(results)
建立另一個新的程式碼資料格。
在程式碼資料格中,輸出資料框架中前 10 個項目。 執行此資料格。
df_cosmos.head(10)
觀察執行命令的輸出。
|
動作 |
ItemRevenue |
Country |
項目 |
|
0 |
已購買 |
19.99 |
北馬其頓 |
扣領襯衫 |
|
1 |
已檢視 |
12.00 |
巴布亞紐幾內亞 |
項鍊 |
|
2 |
已檢視 |
25.00 |
斯洛伐克 (斯洛伐克共和國) |
羊毛衣 |
|
3 |
已購買 |
14.00 |
塞內加爾 |
拖鞋 |
|
4 |
已檢視 |
50.00 |
巴拿馬 |
牛仔短褲 |
|
5 |
已檢視 |
14.00 |
塞內加爾 |
拖鞋 |
|
6 |
已新增 |
14.00 |
塞內加爾 |
拖鞋 |
|
7 |
已新增 |
50.00 |
巴拿馬 |
牛仔短褲 |
|
8 |
已購買 |
33.00 |
巴勒斯坦領土 |
紅色上衣 |
|
9 |
已檢視 |
30.00 |
馬爾他 |
綠色毛衣 |
建立另一個新的程式碼資料格。
在程式碼資料格中,匯入 pandas 套件以自訂資料框架的輸出。 執行此資料格。
import pandas as pd
df_cosmos.groupby("Item").size().reset_index()
觀察執行命令的輸出。
|
項目 |
Test |
|
0 |
拖鞋 |
66 |
|
1 |
項鍊 |
55 |
|
2 |
運動鞋 |
111 |
|
... |
... |
... |
|
45 |
風衣外套 |
56 |
建立新的程式碼資料格。
在程式碼資料格中,新增程式碼以使用 SDK 執行 SQL 查詢,將查詢的輸出儲存在 List<T> 類型的變數中,名為 results。
using System.Collections.Generic;
var query = new QueryDefinition(
query: "SELECT c.Action, c.Price, c.Country, c.Item FROM c"
);
FeedIterator<Record> feed = container.GetItemQueryIterator<Record>(
queryDefinition: query
);
var results = new List<Record>();
while (feed.HasMoreResults)
{
FeedResponse<Record> response = await feed.ReadNextAsync();
foreach (Record result in response)
{
results.Add(result);
}
}
建立另一個新的程式碼資料格。
在程式碼資料格中建立字典,將項目欄位的唯一排列新增為索引鍵,並將價格欄位中的總和新增為值。 這會為每個項目提供總銷售額。 執行此資料格。
var dictionary = new Dictionary<string, decimal>();
foreach(var result in results)
{
if (dictionary.ContainsKey(result.Item)) {
dictionary[result.Item] += result.Price;
}
else {
dictionary.TryAdd (result.Item, result.Price);
}
}
dictionary
觀察具有 [Item] 和 [Price] 欄位唯一組合的輸出。
...
Black Tee: 603
Flannel Shirt: 1199.40
Socks: 210.00
Rainjacket: 2695
...
下一步