Azure Cosmos DB:使用 Azure Cosmos DB SQL API 帳戶建置 Python 應用程式Azure Cosmos DB: Build a Python application using Azure Cosmos DB SQL API account

Azure Cosmos DB 是 Microsoft 的全域分散式多模型資料庫服務。Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. 您可以快速建立及查詢文件、索引鍵/值、整個資料行及圖形資料庫。You can quickly create and query documents, key/value, wide column and graph databases. 所有這些作業都受惠於 Azure Cosmos DB 的散發和調整。All of these operations benefit from the distribution and scale of Azure Cosmos DB.

此快速入門示範如何使用 Azure 入口網站建立 Azure Cosmos DB SQL API 帳戶、文件資料庫和容器。This quickstart demonstrates how to create an Azure Cosmos DB SQL API account, document database, and container using the Azure portal. 接著,您要建置和執行以適用於 SQL API 的 Python SDK 為基礎的主控台應用程式。You then build and run a console app built with the Python SDK for SQL API. 本快速入門使用 3.0 版的 Python SDKThis quickstart uses version 3.0 of the Python SDK.

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin. 您可以免費試用 Azure Cosmos DB,無須 Azure 訂用帳戶,也無須任何費用和約定付款。You can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. 或者,您也可以搭配使用 Azure Cosmos DB 模擬器https://localhost:8081 的 URI。Or, you can use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. 驗證要求中會提供主索引鍵。The Primary Key is provided in Authenticating requests.如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin. 您可以免費試用 Azure Cosmos DB,無須 Azure 訂用帳戶,也無須任何費用和約定付款。You can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. 或者,您也可以搭配使用 Azure Cosmos DB 模擬器https://localhost:8081 的 URI。Or, you can use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. 驗證要求中會提供主索引鍵。The Primary Key is provided in Authenticating requests.

必要條件Prerequisites

建立資料庫帳戶Create a database account

  1. 登入 Azure 入口網站Sign in to the Azure portal.

  2. 選取 [建立資源] > [資料庫] > [Azure Cosmos DB] 。Select Create a resource > Databases > Azure Cosmos DB.

    Azure 入口網站資料庫窗格

  3. 在 [建立 Azure Cosmos DB 帳戶] 頁面上,輸入新 Azure Cosmos 帳戶的基本設定。On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    設定Setting Value 說明Description
    SubscriptionSubscription 訂用帳戶名稱Subscription name 選取要用於此 Azure Cosmos 帳戶的 Azure 訂用帳戶。Select the Azure subscription that you want to use for this Azure Cosmos account.
    資源群組Resource Group 資源群組名稱Resource group name 選取資源群組,或選取 [新建] ,然後輸入新資源群組的唯一名稱。Select a resource group, or select Create new, then enter a unique name for the new resource group.
    帳戶名稱Account Name 輸入唯一名稱Enter a unique name 輸入名稱來識別您的 Azure Cosmos 帳戶。Enter a name to identify your Azure Cosmos account. 因為 documents.azure.com 會附加到您所提供的識別碼以建立 URI,請使用唯一識別碼。Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    識別碼只能包含小寫字母、數字及連字號 (-) 字元。The ID can only contain lowercase letters, numbers, and the hyphen (-) character. 其長度必須介於 3 到 31 個字元之間。It must be between 3-31 characters in length.
    APIAPI Core (SQL)Core (SQL) API 會決定要建立的帳戶類型。The API determines the type of account to create. Azure Cosmos DB 提供五個 API:Core(SQL) 和 MongoDB (適用於文件資料)、Gremlin (適用於圖形資料)、Azure 資料表及 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. 目前,您必須為每個 API 建立個別個帳戶。Currently, you must create a separate account for each API.

    選取 [Core(SQL)] ,以使用 SQL 語法建立文件資料庫並進行查詢。Select Core (SQL) to create a document database and query by using SQL syntax.

    進一步了解 SQL APILearn more about the SQL API.
    LocationLocation 選取最接近使用者的區域Select the region closest to your users 選取用來裝載 Azure Cosmos DB 帳戶的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用最接近使用者的位置,讓他們能以最快速度存取資料。Use the location that is closest to your users to give them the fastest access to the data.

    Azure Cosmos DB 的新帳戶頁面

  4. 選取 [檢閱 + 建立] 。Select Review + create. 您可以略過 [網路] 和 [標記] 區段。You can skip the Network and Tags sections.

  5. 檢閱帳戶設定,然後選取 [建立] 。Review the account settings, and then select Create. 建立帳戶需要幾分鐘的時間。It takes a few minutes to create the account. 等候入口網站頁面顯示 [您的部署已完成] 訊息。Wait for the portal page to display Your deployment is complete.

    Azure 入口網站的 [通知] 窗格

  6. 選取 [移至資源] 以移至 Azure Cosmos DB 帳戶頁面。Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帳戶頁面

新增容器Add a container

您現在可以在 Azure 入口網站中使用 [資料總管] 工具,建立資料庫和容器。You can now use the Data Explorer tool in the Azure portal to create a database and container.

  1. 選取 [資料總管] > [新增容器] 。Select Data Explorer > New Container.

    [新增容器] 區域會顯示在最右邊,您可能需要向右捲動才能看到它。The Add Container area is displayed on the far right, you may need to scroll right to see it.

    Azure 入口網站資料總管,[新增容器] 窗格

  2. 在 [新增容器] 頁面上,輸入新容器的設定。In the Add container page, enter the settings for the new container.

    設定Setting 建議的值Suggested value 說明Description
    資料庫識別碼Database ID 工作Tasks 輸入 ToDoList 作為新資料庫的名稱。Enter ToDoList as the name for the new database. 資料庫名稱必須包含從 1 到 255 個字元,且不能包含 /, \\, #, ? 或尾端空格。Database names must contain from 1 through 255 characters, and they cannot contain /, \\, #, ?, or a trailing space. 核取 [佈建資料庫輸送量] 選項,它可讓您在資料庫中的所有容器內共用佈建到資料庫的輸送量。Check the Provision database throughput option, it allows you to share the throughput provisioned to the database across all the containers within the database. 此選項也有助於節省成本。This option also helps with cost savings.
    輸送量Throughput 400400 讓輸送量保持在每秒 400 個要求單位 (RU/秒)。Leave the throughput at 400 request units per second (RU/s). 如果您想要降低延遲,稍後可以相應增加輸送量。If you want to reduce latency, you can scale up the throughput later.
    容器識別碼Container ID 項目Items 輸入 Items 作為新容器的名稱。Enter Items as the name for your new container. 容器識別碼與資料庫名稱具有相同的字元需求。Container IDs have the same character requirements as database names.
    分割區索引鍵Partition key /類別/category 本文中所述的範例使用 /category 作為分割區索引鍵。The sample described in this article uses /category as the partition key.

    除了上述的設定,您可以選擇性地為容器新增 [唯一索引鍵] 。In addition to the preceding settings, you can optionally add Unique keys for the container. 在此範例中,讓我們將欄位保留空白。Let's leave the field empty in this example. 唯一索引鍵可讓開發人員在資料庫中新增一層資料完整性。Unique keys provide developers with the ability to add a layer of data integrity to the database. 您可在建立容器時建立唯一索引鍵原則,以確保每個資料分割索引鍵一或多個值的唯一性。By creating a unique key policy while creating a container, you ensure the uniqueness of one or more values per partition key. 若要深入了解,請參閱 Azure Cosmos DB 中的唯一索引鍵一文。To learn more, refer to the Unique keys in Azure Cosmos DB article.

    選取 [確定] 。Select OK. [資料總管] 會顯示新的資料庫和容器。The Data Explorer displays the new database and container.

新增範例資料Add sample data

您現在可以使用 [資料總管] 將資料新增至您的新容器。You can now add data to your new container using Data Explorer.

  1. 在 [資料總管] 中,展開 Tasks 資料庫,然後展開 Items 容器。From the Data Explorer, expand the Tasks database, expand the Items container. 選取 [項目] ,然後選取 [新增項目] 。Select Items, and then select New Item.

    在 Azure 入口網站的 [資料總管] 中建立新文件

  2. 現在將文件新增至具有下列結構的容器。Now add a document to the container with the following structure.

    {
        "id": "1",
        "category": "personal",
        "name": "groceries",
        "description": "Pick up apples and strawberries.",
        "isComplete": false
    }
    
  3. 將 json 新增至 [文件] 索引標籤後,選取 [儲存] 。Once you've added the json to the Documents tab, select Save.

    將 json 資料複製在 Azure 入口網站的 [資料總管] 中並選取 [儲存]

  4. 多建立並儲存一份文件,以便在其中插入 id 屬性的唯一值,並適當變更其他屬性。Create and save one more document where you insert a unique value for the id property, and change the other properties as you see fit. 新文件可擁有您想要的任何結構,因為 Azure Cosmos DB 不會對您的資料強加任何結構描述。Your new documents can have any structure you want as Azure Cosmos DB doesn't impose any schema on your data.

查詢資料Query your data

您可以在 [資料總管] 中,使用查詢來擷取和篩選您的資料。You can use queries in Data Explorer to retrieve and filter your data.

  1. 在 [資料總管] 中的 [文件] 索引標籤頂端,檢閱預設查詢 SELECT * FROM cAt the top of the Documents tab in Data Explorer, review the default query SELECT * FROM c. 此查詢會依照識別碼順序擷取並顯示集合中的所有文件。This query retrieves and displays all documents in the collection in ID order.

    [資料總管] 中的預設查詢為 SELECT * FROM c

  2. 若要變更查詢,請選取 [編輯篩選條件] ,以 ORDER BY c._ts DESC 取代預設查詢,然後選取 [套用篩選條件] 。To change the query, select Edit Filter, replace the default query with ORDER BY c._ts DESC, and then select Apply Filter.

    新增 ORDER BY c._ts DESC 並按一下 [套用篩選],以變更預設查詢

    經過修改的查詢會根據文件的時間戳記,依遞減順序顯示文件,因此現會最先列出您的第二份文件。The modified query displays the documents in descending order based on their time stamp, so now your second document is listed first.

    已將查詢變更為 ORDER BY c._ts DESC 並按一下 [套用篩選]

若您熟悉 SQL 語法,則可在查詢述詞方塊中輸入任何支援的 SQL 查詢If you're familiar with SQL syntax, you can enter any supported SQL queries in the query predicate box. 您也可以使用 [資料總管] 來建立伺服器端商務邏輯的預存程序、UDF 和觸發程序。You can also use Data Explorer to create stored procedures, UDFs, and triggers for server-side business logic.

[資料總管] 可讓您透過 Azure 入口網站輕鬆存取 API 中所有可用的內建程式設計資料存取功能。Data Explorer provides easy Azure portal access to all of the built-in programmatic data access features available in the APIs. 您也可以使用入口網站來調整輸送量、取得金鑰和連接字串,以及檢閱 Azure Cosmos DB 帳戶的計量和 SLA。You also use the portal to scale throughput, get keys and connection strings, and review metrics and SLAs for your Azure Cosmos DB account.

複製範例應用程式Clone the sample application

現在,我們將從 GitHub 複製 SQL API 應用程式、設定連接字串,然後加以執行。Now let's clone a SQL API app from GitHub, set the connection string, and run it.

  1. 開啟命令提示字元,建立名為 git-samples 的新資料夾,然後關閉命令提示字元。Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "git-samples"
    

    如果您使用 bash 提示字元,應改為使用下列命令︰If you are using a bash prompt, you should instead use the following command:

    mkdir "git-samples"
    
  2. 開啟 git 終端機視窗 (例如 git bash),並使用 cd 命令變更至要安裝範例應用程式的新資料夾。Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "git-samples"
    
  3. 執行下列命令來複製範例存放庫。Run the following command to clone the sample repository. 此命令會在您的電腦上建立範例應用程式副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-python-getting-started.git
    

更新您的連接字串Update your connection string

現在,返回 Azure 入口網站以取得連接字串資訊,並將它複製到應用程式中。Now go back to the Azure portal to get your connection string information and copy it into the app.

  1. Azure 入口網站的 Azure Cosmos 帳戶中,選取左側導覽列中的 [金鑰] 。In the Azure portal, in your Azure Cosmos account, in the left navigation select Keys. 在下一個步驟中,您將使用畫面右側的複製按鈕,將 URI主要金鑰複製到 CosmosGetStarted.py 檔案。You'll use the copy buttons on the right side of the screen to copy the URI and Primary Key into the CosmosGetStarted.py file in the next step.

    在 Azure 入口網站的 [金鑰] 刀鋒視窗中檢視並複製存取金鑰

  2. 在 Visual Studio Code 中開啟 \git-samples\azure-cosmos-db-python-getting-started 中的 CosmosGetStarted.py 檔案。Open the CosmosGetStarted.py file in \git-samples\azure-cosmos-db-python-getting-started in Visual Studio Code.

  3. 從入口網站複製您的 URI 值 (使用 [複製] 按鈕),並使它成為 CosmosGetStarted.py 中的端點金鑰值。Copy your URI value from the portal (using the copy button) and make it the value of the endpoint key in CosmosGetStarted.py.

    'ENDPOINT': 'https://FILLME.documents.azure.com',

  4. 然後,從入口網站複製您的主要金鑰值,並使它成為 CosmosGetStarted.py 中的 config.PRIMARYKEY 值。Then copy your PRIMARY KEY value from the portal and make it the value of the config.PRIMARYKEY in CosmosGetStarted.py. 您現已更新應用程式,使其具有與 Azure Cosmos DB 通訊所需的所有資訊。You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

    'PRIMARYKEY': 'FILLME',

  5. 儲存 CosmosGetStarted.py 檔案。Save the CosmosGetStarted.py file.

檢閱程式碼Review the code

此為選用步驟。This step is optional. 了解以程式碼建立的資料庫資源,或直接跳到更新您的連接字串Learn about the database resources created in code, or skip ahead to Update your connection string.

請注意,如果您熟悉舊版 Python SDK,您可能已習慣看到「集合」和「文件」等字詞。Note, if you are familiar with the previous version of the Python SDK, you may be used to seeing the terms "collection" and "document." 因為 Azure Cosmos DB 支援多個 API 模型,3.0+ 版的 Python SDK 會使用「容器」這個泛用字詞,此字詞可能是用來說明容器內容的集合、圖表或資料表和「項目」。Because Azure Cosmos DB supports multiple API models, version 3.0+ of the Python SDK uses the generic terms "container,", which may be a collection, graph, or table and "item" to describe the content of the container.

下列程式碼片段全部取自 CosmosGetStarted.py 檔案。The following snippets are all taken from the CosmosGetStarted.py file.

  • 已初始化 CosmosClient。The CosmosClient is initialized. 請務必如更新連接字串一節所述,更新「端點」和「主要金鑰」值。Make sure to update the "Endpoint" and "master key" values as described in the Update your connection string section.

    # Initialize the Cosmos client
    client = cosmos_client.CosmosClient(url_connection=config['ENDPOINT'], auth={'masterKey': config['MASTERKEY']})
    
  • 已建立新資料庫。A new database is created.

    # Create a database
    db = client.CreateDatabase({ 'id': config['DATABASE'] })
    
  • 已建立新的容器。A new container is created.

    # Create container options
    options = {
        'offerThroughput': 400
    }
    
    # Create a container
    container = client.CreateContainer(db['_self'], container_definition, options)
    
  • 有些項目會新增至容器。Some items are added to the container.

    # Create and add some items to the container
    item1 = client.CreateItem(container['_self'], {
        'serverId': 'server1',
        'Web Site': 0,
        'Cloud Service': 0,
        'Virtual Machine': 0,
        'message': 'Hello World from Server 1!'
        }
    )
    
    item2 = client.CreateItem(container['_self'], {
        'serverId': 'server2',
        'Web Site': 1,
        'Cloud Service': 0,
        'Virtual Machine': 0,
        'message': 'Hello World from Server 2!'
        }
    )
    
  • 已使用 SQL 執行查詢A query is performed using SQL

    query = {'query': 'SELECT * FROM server s'}
    
    options = {}
    options['enableCrossPartitionQuery'] = True
    options['maxItemCount'] = 2
    
    result_iterable = client.QueryItems(container['_self'], query, options)
    for item in iter(result_iterable):
        print(item['message'])
    

執行應用程式Run the app

  1. 在 Visual Studio Code 中,選取 [檢視] > [命令選擇區] 。In Visual Studio Code, select View > Command Palette.

  2. 在提示字元中,輸入 Python:Select Interpreter,然後選取要使用的 Python 版本。At the prompt, enter Python: Select Interpreter and then select the version of Python to use.

    Visual Studio Code 中的頁尾會更新以指出選取的解譯器。The Footer in Visual Studio Code is updated to indicate the interpreter selected.

  3. 選取 [檢視] > [整合式終端機] 以開啟 Visual Studio Code 整合式終端機。Select View > Integrated Terminal to open the Visual Studio Code integrated terminal.

  4. 在整合式終端機視窗中,確保您在 azure-cosmos-db-python-getting-started 資料夾中。In the integrated terminal window, ensure you are in the azure-cosmos-db-python-getting-started folder. 如果不是,請執行下列命令來切換至範例資料夾。If not, run the following command to switch to the sample folder.

    cd "\git-samples\azure-cosmos-db-python-getting-started"`
    
  5. 執行以下命令來安裝 azure-cosmos 套件。Run the following command to install the azure-cosmos package.

    pip3 install azure-cosmos
    

    如果您收到有關在嘗試安裝 azure-cosmos 時拒絕存取的錯誤,您必須以系統管理員身分執行 VS CodeIf you get an error about access being denied when attempting to install azure-cosmos, you'll need to run VS Code as an administrator.

  6. 執行下列命令以執行範例,並且在 Azure Cosmos dB 中建立和儲存新文件。Run the following command to run the sample and create and store new documents in Azure Cosmos dB.

    python CosmosGetStarted.py
    
  7. 若要確認已建立並儲存新項目,請在 Azure 入口網站中,選取 [資料總管] ,依序展開 [coll] 、[文件] ,然後選取 [server1] 文件。To confirm the new items were created and saved, in the Azure portal, select Data Explorer, expand coll, expand Documents, and then select the server1 document. Server1 文件內容符合整合式終端機視窗中傳回的內容。The server1 document contents match the content returned in the integrated terminal window.

    在 Azure 入口網站中檢視新文件

在 Azure 入口網站中檢閱 SLAReview SLAs in the Azure portal

Azure 入口網站會監視您的 Cosmos DB 帳戶輸送量、儲存體、可用性、延遲和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服務等級協定 (SLA) 相關聯的計量圖表會顯示相較於實際效能的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此計量套件可讓您以更透明的方式監視監視 SLA。This suite of metrics makes monitoring your SLAs transparent.

若要檢閱計量和 SLA:To review metrics and SLAs:

  1. 在您的 Cosmos DB 帳戶導覽功能表中,選取 [計量] 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 選取一個索引標籤 (例如 [延遲] ),並在右側選取時間範圍。Select a tab such as Latency, and select a timeframe on the right. 比較圖表中的實際SLA 的資料行。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 計量套件

  3. 檢閱其他索引標籤中的計量。Review the metrics on the other tabs.

清除資源Clean up resources

完成您的 Web 應用程式和 Azure Cosmos DB 帳戶之後,您可以將建立的 Azure 資源刪除,以免產生更多費用。When you're done with your web app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要刪除資源:To delete the resources:

  1. 在 Azure 入口網站中,選取最左邊的 [資源群組] 。In the Azure portal, select Resource groups on the far left. 若已摺疊左側功能表,請選取展開按鈕加以展開。If the left menu is collapsed, select Expand button to expand it.

  2. 選取您在本快速入門中建立的資源群組。Select the resource group you created for this quickstart.

    Azure 入口網站中的計量

  3. 在新視窗中,選取 [刪除資源群組] 。In the new window, select Delete resource group.

    Azure 入口網站中的計量

  4. 在下個視窗中輸入要刪除的資源群組名稱,然後選取 [刪除] 。In the next window, enter the name of the resource group to delete, and then select Delete.

後續步驟Next steps

在本快速入門中,您已了解如何建立 Azure Cosmos 帳戶、如何使用 [資料總管] 建立容器,以及如何執行應用程式。In this quickstart, you've learned how to create an Azure Cosmos account, create a container using the Data Explorer, and run an app. 您現在可以將其他資料匯入到 Cosmos DB 帳戶。You can now import additional data to your Cosmos DB account.