快速入門:使用 Python 和 Azure 入口網站在 Azure Cosmos DB 中建立圖形資料庫Quickstart: Create a graph database in Azure Cosmos DB using Python and the Azure portal

本快速入門說明如何使用 Python 與 Azure Cosmos DB Gremlin API,透過從 GitHub 複製範例來組建主控台應用程式。This quickstart shows how to use Python and the Azure Cosmos DB Gremlin API to build a console app by cloning an example from GitHub. 本快速入門也會逐步引導您使用網頁型 Azure 入口網站建立 Azure Cosmos DB 帳戶。This quickstart also walks you through the creation of an Azure Cosmos DB account by using the web-based Azure portal.

Azure Cosmos DB 是 Microsoft 的全域分散式多模型資料庫服務。Azure Cosmos DB is Microsoft's globally distributed multi-model database service. 您可以快速建立及查詢文件、資料表、索引鍵/值及圖形資料庫,所有這些都受惠於位於 Azure Cosmos DB 核心的全域散發和水平調整功能。You can quickly create and query document, table, key-value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Azure Cosmos DB.

注意

此快速入門需要 2017 年 12 月 20 日之後建立的圖形資料庫帳戶。This quickstart requires a graph database account created after December 20th, 2017. 現有帳戶在移轉至正式運作之後便會支援 Python。Existing accounts will support Python once they’re migrated to general availability.

必要條件Prerequisites

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.或者,您可以免費試用 Azure Cosmos DB,無須 Azure 訂用帳戶,也無須任何費用和約定付款。如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin. Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments.

此外:In addition:

建立資料庫帳戶Create a database account

您必須先使用 Azure Cosmos DB 建立 Gremlin (圖形) 資料庫帳戶,才可以建立圖形資料庫。Before you can create a graph database, you need to create a Gremlin (Graph) database account with Azure Cosmos DB.

  1. 在新的瀏覽器視窗中,登入 Azure 入口網站In a new browser window, sign in to the Azure portal.

  2. 按一下 [建立資源] > [資料庫] > [Azure Cosmos DB] 。Click Create a resource > Databases > Azure Cosmos DB.

    Azure 入口網站的 [資料庫] 窗格

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

    設定Setting Value 說明Description
    訂用帳戶Subscription 您的訂用帳戶Your subscription 選取要用於此 Azure Cosmos DB 帳戶的 Azure 訂用帳戶。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    資源群組Resource Group 新建Create new

    然後輸入識別碼中所提供的同一個唯一名稱Then enter the same unique name as provided in ID
    選取 [建立新的] 。Select Create new. 然後為您的帳戶輸入新的資源群組名稱。Then enter a new resource-group name for your account. 為求簡化,請使用和識別碼相同的名稱。For simplicity, use the same name as your ID.
    帳戶名稱Account Name 輸入唯一名稱Enter a unique name 輸入唯一名稱來識別您的 Azure Cosmos DB 帳戶。Enter a unique name to identify your Azure Cosmos DB 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 use only lowercase letters, numbers, and the hyphen (-) character. 長度必須介於 3 到 31 個字元之間。It must be between 3 and 31 characters in length.
    APIAPI Gremlin (圖形)Gremlin (graph) API 會決定要建立的帳戶類型。The API determines the type of account to create. Azure Cosmos DB 提供五個 API:Core(SQL) (適用於文件資料庫)、Gremlin (適用於圖形資料庫)、MongoDB (適用於文件資料庫)、「Azure 資料表」及 Cassandra。Azure Cosmos DB provides five APIs: Core(SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. 目前,您必須為每個 API 建立個別個帳戶。Currently, you must create a separate account for each API.

    選取 [Gremlin (圖形)] ,因為在此快速入門中,您會建立可搭配 Gremlin API 使用的資料表。Select Gremlin (graph) because in this quickstart you are creating a table that works with the Gremlin API.

    深入了解圖形 APILearn more about the Graph API.
    位置Location 選取最接近使用者的區域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's closest to your users to give them the fastest access to the data.

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

    Azure Cosmos DB 的新帳戶刀鋒視窗

  4. 建立帳戶需要幾分鐘的時間。The account creation takes a few minutes. 等候入口網站顯示 [恭喜!已建立您的 Azure Cosmos DB 帳戶] 頁面。Wait for the portal to display the Congratulations! Your Azure Cosmos DB account was created page.

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

新增圖形Add a graph

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

  1. 選取 [資料總管] > [新增圖形] 。Select Data Explorer > New Graph.

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

    Azure 入口網站資料總管 [新增圖形] 頁面

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

    設定Setting 建議的值Suggested value 說明Description
    資料庫識別碼Database ID sample-databasesample-database 輸入 sample-database 作為新資料庫的名稱。Enter sample-database as the name for the new database. 資料庫名稱的長度必須介於 1 到 255 個字元,且不能包含 / \ # ? 或尾端空格。Database names must be between 1 and 255 characters, and cannot contain / \ # ? or a trailing space.
    ThroughputThroughput 400 RU400 RUs 將輸送量變更為每秒 400 個要求單位 (RU/秒)。Change the throughput to 400 request units per second (RU/s). 如果您想要降低延遲,稍後可以相應增加輸送量。If you want to reduce latency, you can scale up the throughput later.
    圖形識別碼Graph ID sample-graphsample-graph 輸入 sample-graph 作為新集合的名稱。Enter sample-graph as the name for your new collection. 圖形名稱與資料庫識別碼具有相同的字元需求。Graph names have the same character requirements as database IDs.
    資料分割索引鍵Partition Key /pk/pk 所有 Cosmos DB 帳戶都需要分割索引鍵,才能進行水準調整。All Cosmos DB accounts need a partition key to horizontally scale. 了解如何在圖表資料分割一文中選取適當的分割區索引鍵。Learn how to select an appropriate partition key in the Graph Data Partitioning article.
  3. 填妥表單後,選取 [確定] 。Once the form is filled out, select OK.

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

現在讓我們切換為使用程式碼。Now let's switch to working with code. 我們將從 GitHub 複製 Gremlin API 應用程式、設定連接字串,然後加以執行。Let's clone a Gremlin API app from GitHub, set the connection string, and run it. 您會看到,以程式設計方式來處理資料有多麼的容易。You'll see how easy it is to work with data programmatically.

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

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

    cd "C:\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-graph-python-getting-started.git
    

檢閱程式碼Review the code

此為選用步驟。This step is optional. 若您想要瞭解如何在程式碼中建立資料庫資源,則可檢閱下列程式碼片段。If you're interested in learning how the database resources are created in the code, you can review the following snippets. 程式碼片段皆取自 C:\git-samples\azure-cosmos-db-graph-python-getting-started\ 資料夾中的 connect.py 檔案。The snippets are all taken from the connect.py file in the C:\git-samples\azure-cosmos-db-graph-python-getting-started\ folder. 或者也可以直接跳至更新您的連接字串Otherwise, you can skip ahead to Update your connection string.

  • Gremlin client 是於 connect.py 的第 104 行初始化:The Gremlin client is initialized in line 104 in connect.py:

    ...
    client = client.Client('wss://<YOUR_ENDPOINT>.gremlin.cosmosdb.azure.com:443/','g', 
        username="/dbs/<YOUR_DATABASE>/colls/<YOUR_COLLECTION_OR_GRAPH>", 
        password="<YOUR_PASSWORD>")
    ...
    
  • connect.py 檔案開頭會宣告一連串的 Gremlin 步驟。A series of Gremlin steps are declared at the beginning of the connect.py file. 接著會使用 client.submitAsync() 方法執行那些步驟:They are then executed using the client.submitAsync() method:

    client.submitAsync(_gremlin_cleanup_graph)
    

更新您的連線資訊Update your connection information

現在,返回 Azure 入口網站以取得連線資訊,並將其複製到應用程式中。Now go back to the Azure portal to get your connection information and copy it into the app. 這些設定可讓您的應用程式與託管資料庫進行通訊。These settings enable your app to communicate with your hosted database.

  1. Azure 入口網站中,按一下 [金鑰] 。In the Azure portal, click Keys.

    複製 URI 值的第一個部分。Copy the first portion of the URI value.

    在 Azure 入口網站的 [金鑰] 頁面中,檢視並複製存取金鑰

  2. 開啟 connect.py 檔案,並在第 104 行將 URI 值貼至下列程式碼的 <YOUR_ENDPOINT> 上:Open the connect.py file and in line 104 paste the URI value over <YOUR_ENDPOINT> in here:

    client = client.Client('wss://<YOUR_ENDPOINT>.gremlin.cosmosdb.azure.com:443/','g', 
        username="/dbs/<YOUR_DATABASE>/colls/<YOUR_COLLECTION_OR_GRAPH>", 
        password="<YOUR_PASSWORD>")
    

    用戶端物件的 URI 部分現在看起來應該類似以下程式碼:The URI portion of the client object should now look similar to this code:

    client = client.Client('wss://test.gremlin.cosmosdb.azure.com:443/','g', 
        username="/dbs/<YOUR_DATABASE>/colls/<YOUR_COLLECTION_OR_GRAPH>", 
        password="<YOUR_PASSWORD>")
    
  3. 變更 client 物件的第二個參數,來取代 <YOUR_DATABASE><YOUR_COLLECTION_OR_GRAPH> 字串。Change the second parameter of the client object to replace the <YOUR_DATABASE> and <YOUR_COLLECTION_OR_GRAPH> strings. 如果您使用建議的值,參數看起來應該類似以下程式碼:If you used the suggested values, the parameter should look like this code:

    username="/dbs/sample-database/colls/sample-graph"

    整個 client 物件現在看起來應該類似以下程式碼:The entire client object should now look like this code:

    client = client.Client('wss://test.gremlin.cosmosdb.azure.com:443/','g', 
        username="/dbs/sample-database/colls/sample-graph", 
        password="<YOUR_PASSWORD>")
    
  4. 在 Azure 入口網站中,使用複製按鈕複製 PRIMARY KEY,然後將其貼上至 password=<YOUR_PASSWORD> 參數中的 <YOUR_PASSWORD>In the Azure portal, use the copy button to copy the PRIMARY KEY and paste it over <YOUR_PASSWORD> in the password=<YOUR_PASSWORD> parameter.

    整個 client 物件定義現在看起來應該類似以下程式碼:The entire client object definition should now look like this code:

    client = client.Client('wss://test.gremlin.cosmosdb.azure.com:443/','g', 
        username="/dbs/sample-database/colls/sample-graph", 
        password="asdb13Fadsf14FASc22Ggkr662ifxz2Mg==")
    
  5. 儲存 connect.py 檔案。Save the connect.py file.

執行主控台應用程式Run the console app

  1. 在 git 終端機視窗中,cd 至 azure-cosmos-db-graph-python-getting-started 資料夾。In the git terminal window, cd to the azure-cosmos-db-graph-python-getting-started folder.

    cd "C:\git-samples\azure-cosmos-db-graph-python-getting-started"
    
  2. 在 git 終端機視窗中,使用下列命令來安裝所需的 Python 套件。In the git terminal window, use the following command to install the required Python packages.

    pip install -r requirements.txt
    
  3. 在 git 終端機視窗中,使用下列命令來啟動 Python 應用程式。In the git terminal window, use the following command to start the Python application.

    python connect.py
    

    終端機視窗會顯示新增至圖形的頂點和邊緣。The terminal window displays the vertices and edges being added to the graph.

    如果遇到逾時錯誤,請檢查您已在更新您的連線資訊中正確更新連線資訊,也請嘗試重新執行最後一個命令。If you experience timeout errors, check that you updated the connection information correctly in Update your connection information, and also try running the last command again.

    程式停止後,按 Enter,然後在網際網路瀏覽器中切換回 Azure 入口網站。Once the program stops, press Enter, then switch back to the Azure portal in your internet browser.

檢閱並新增範例資料Review and add sample data

在插入頂點和邊緣之後,您現在可以移回 [資料總管] 並查看已新增到圖行的頂點,然後新增額外的資料點。After the vertices and edges are inserted, you can now go back to Data Explorer and see the vertices added to the graph, and add additional data points.

  1. 按一下 [資料總管] ,展開 sample-graph,按一下 [圖形] ,然後再按一下 [套用篩選條件] 。Click Data Explorer, expand sample-graph, click Graph, and then click Apply Filter.

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

  2. 在 [結果] 清單中,請注意圖形中已新增三個使用者。In the Results list, notice three new users are added to the graph. 您可以拖放移動周圍的頂點、捲動滑鼠滾輪執行縮放、使用雙箭號展開圖形大小。You can move the vertices around by dragging and dropping, zoom in and out by scrolling the wheel of your mouse, and expand the size of the graph with the double-arrow.

    Azure 入口網站的資料總管之圖形中的新頂點

  3. 現在來加入一些新使用者。Let's add a few new users. 按一下 [新增頂點] 按鈕,將資料新增至您的圖形。Click the New Vertex button to add data to your graph.

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

  4. 輸入人員的標籤。Enter a label of person.

  5. 按一下 [新增屬性] ,以新增以下各項屬性。Click Add property to add each of the following properties. 請注意,您可以在圖形中為每個人建立獨特的屬性。Notice that you can create unique properties for each person in your graph. 只需要識別碼索引鍵。Only the id key is required.

    索引鍵key valuevalue 注意Notes
    pkpk /pk/pk
    idid ashleyashley 頂點的唯一識別碼。The unique identifier for the vertex. 如果您未指定識別碼,系統會為您產生一個。If you don't specify an id, one is generated for you.
    gendergender femalefemale
    techtech javajava

    注意

    在本快速入門中,建立非資料分割集合。In this quickstart create a non-partitioned collection. 不過,如果您藉由在集合建立期間指定資料分割索引鍵來建立資料分割集合,您就必須包含資料分割索引鍵作為每個新頂點的索引鍵。However, if you create a partitioned collection by specifying a partition key during the collection creation, then you need to include the partition key as a key in each new vertex.

  6. 按一下 [確定] 。Click OK. 您可能需要展開畫面,才能在螢幕底部看到 [確定] 。You may need to expand your screen to see OK on the bottom of the screen.

  7. 再次按一下 [新增頂點] 並新增額外的新使用者。Click New Vertex again and add an additional new user.

  8. 輸入人員的標籤。Enter a label of person.

  9. 按一下 [新增屬性] ,以新增以下各項屬性:Click Add property to add each of the following properties:

    索引鍵key valuevalue 注意Notes
    pkpk /pk/pk
    idid rakeshrakesh 頂點的唯一識別碼。The unique identifier for the vertex. 如果您未指定識別碼,系統會為您產生一個。If you don't specify an id, one is generated for you.
    gendergender malemale
    schoolschool MITMIT
  10. 按一下 [確定] 。Click OK.

  11. 按一下 [套用篩選條件] 按鈕,預設的 g.V() 篩選條件會顯示圖形中的所有值。Click the Apply Filter button with the default g.V() filter to display all the values in the graph. 所有使用者現在會顯示在 [結果] 清單中。All of the users now show in the Results list.

    隨著您新增更多的資料,您可以使用篩選條件來限制您的結果。As you add more data, you can use filters to limit your results. 依預設,[資料總管] 會使用 g.V() 擷取圖形中的所有頂點。By default, Data Explorer uses g.V() to retrieve all vertices in a graph. 您可將其變更為不同的圖形查詢 (例如 g.V().count()),以使用 JSON 格式傳回圖形中所有頂點的計數。You can change it to a different graph query, such as g.V().count(), to return a count of all the vertices in the graph in JSON format. 若您變更篩選條件,請將篩選條件變更回 g.V(),然後按一下 [套用篩選條件] ,即可再次顯示所有的結果。If you changed the filter, change the filter back to g.V() and click Apply Filter to display all the results again.

  12. 現在我們可以連線 rakesh 和 ashley。Now we can connect rakesh and ashley. 請確定已在 [結果] 清單中選取 ashley,然後按一下右下方 [目標] 旁邊的編輯按鈕。Ensure ashley is selected in the Results list, then click the edit button next to Targets on lower right side. 您可能需要加寬視窗,才可看到 [屬性] 區域。You may need to widen your window to see the Properties area.

    變更圖形中頂點的目標

  13. 在 [目標] 方塊中輸入 rakesh ,並在 [邊緣標籤] 方塊中輸入 knows ,然後按一下核取方塊。In the Target box type rakesh, and in the Edge label box type knows, and then click the check.

    在 [資料總管] 中新增 ashley 與 rakesh 之間的連線

  14. 現在從 [結果] 清單中選取 rakesh 並查看 ashley 與 rakesh 是否已連線。Now select rakesh from the results list and see that ashley and rakesh are connected.

    [資料總管] 中連線的兩個頂點

    這會完成本教學課程中的資源建立部分。That completes the resource creation part of this tutorial. 您可以繼續將頂點新增至圖形、修改現有的頂點,或是變更查詢。You can continue to add vertexes to your graph, modify the existing vertexes, or change the queries. 現在讓我們檢閱 Azure Cosmos DB 提供的計量,然後再清除資源。Now let's review the metrics Azure Cosmos DB provides, and then clean up the resources.

在 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 DB 帳戶、如何使用 [資料總管] 來建立圖形,以及如何執行應用程式。In this quickstart, you've learned how to create an Azure Cosmos DB account, create a graph using the Data Explorer, and run an app. 您現在可以使用 Gremlin 來建置更複雜的查詢和實作強大的圖形周遊邏輯。You can now build more complex queries and implement powerful graph traversal logic using Gremlin.