快速入門:使用 Azure Cosmos DB SQL API 帳戶建置 Node.js 應用程式Quickstart: Build a Node.js app using Azure Cosmos DB SQL API account

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, key/value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core 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 JavaScript SDK 為基礎的主控台應用程式。You then build and run a console app built on the SQL JavaScript SDK. 此快速入門使用 2.0 版的 JavaScript SDKThis quickstart uses version 2.0 of the JavaScript SDK.

必要條件Prerequisites

如果您沒有 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. 如需要搭配模擬器使用的金鑰,請參閱驗證要求For the key to use with the emulator, see Authenticating requests.

建立資料庫帳戶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
    訂用帳戶Subscription 訂用帳戶名稱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 唯一的名稱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 要建立的帳戶類型The type of account to create 選取 [Core(SQL)] ,以使用 SQL 語法建立文件資料庫並進行查詢。Select Core (SQL) to create a document database and query by using SQL syntax.

    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.

    進一步了解 SQL APILearn more about the SQL API.
    位置Location 最接近使用者的區域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 "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 the new 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-sql-api-nodejs-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. 或者也可以直接跳至更新您的連接字串Otherwise, you can skip ahead to Update your connection string.

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

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

  • 已初始化 CosmosClientThe CosmosClient is initialized.

    const client = new CosmosClient({ endpoint, key });
    
  • 已建立新資料庫。A new database is created.

    const { database } = await client.databases.createIfNotExists({ id: databaseId });
    
  • 已建立新容器 (集合)。A new container (collection) is created.

    const { container } = await client.database(databaseId).containers.createIfNotExists({ id: containerId });
    
  • 已建立項目 (文件)。An item (document) is created.

    const { item } = await client.database(databaseId).container(containerId).items.create(itemBody);
    
  • 已透過 JSON 執行 SQL 查詢。A SQL query over JSON is performed.

      const querySpec = {
        query: 'SELECT VALUE r.children FROM root r WHERE r.lastName = @lastName',
        parameters: [
          {
            name: '@lastName',
            value: 'Andersen'
          }
        ]
      }
    
      const { resources: results } = await client
        .database(databaseId)
        .container(containerId)
        .items.query(querySpec)
        .fetchAll()
      for (var queryResult of results) {
        let resultString = JSON.stringify(queryResult)
        console.log(`\tQuery returned ${resultString}\n`)
      }
    

更新您的連接字串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 click Keys, and then click Read-write Keys. 在下一個步驟中,您將使用畫面右側的複製按鈕,將 URI 和主要金鑰複製到 config.js 檔案。You'll use the copy buttons on the right side of the screen to copy the URI and Primary Key into the config.js file in the next step.

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

  2. 開啟 config.js 檔案。In Open the config.js file.

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

    config.endpoint = "https://FILLME.documents.azure.com"

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

    config.key = "FILLME"

執行應用程式Run the app

  1. 在終端機中執行 npm install 以安裝必要的 npm 模組Run npm install in a terminal to install required npm modules

  2. 在終端機中執行 node app.js 來啟動您的節點應用程式。Run node app.js in a terminal to start your node application.

您現在可以返回 [資料總管],以查看、查詢、修改及使用這項新資料。You can now go back to Data Explorer and see query, modify, and work with this new data.

在 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.

    選取要刪除的資源群組

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

    刪除資源群組

  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.