共用方式為


快速入門:適用於 Node.js 的 Azure Cosmos DB for Apache Gremlin 用戶端程式庫

這很重要

您是否正在尋找一種適用於高擴展性場景的資料庫解決方案,且具有 99.999% 可用性的服務等級協定(SLA)、即時自動擴展,以及跨多個區域的自動容錯切換? 請考慮 適用於 NoSQL 的 Azure Cosmos DB

您是否想要實作線上分析處理 (OLAP) 圖表或移轉現有的 Apache Gremlin 應用程式? 考慮使用 Microsoft Fabric 中的 Graph

開始使用 Azure Cosmos DB for Apache Gremlin 用戶端程式庫,讓 Node.js 儲存、管理和查詢非結構化資料。 請依照本指南中的步驟建立新帳戶、安裝 Node.js 用戶端程式庫、連線到帳戶、執行一般作業,以及查詢最終範例資料。

程式庫原始程式碼 | 套件 (npm)

先決條件

  • Azure 訂用帳戶

    • 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶
  • Node.js 22 或更新

設定

首先,設定本指南的帳號和開發環境。 本節將引導您進行創建帳戶、獲取其憑證,然後準備開發環境。

建立帳戶

首先建立 Apache Gremlin 帳戶的 API。 建立帳戶之後,請建立資料庫和圖形資源。

  1. 如果您還沒有目標資源群組,請使用命令 az group create 在訂用帳戶中建立新的資源群組。

    az group create \
        --name "<resource-group-name>" \
        --location "<location>"
    
  2. 使用命令 az cosmosdb create 來建立具有預設設定的新 Azure Cosmos DB for Apache Gremlin 帳戶。

    az cosmosdb create \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --locations "regionName=<location>" \
        --capabilities "EnableGremlin"
    
  3. 使用az cosmosdb gremlin database create建立新的資料庫,命名為cosmicworks

    az cosmosdb gremlin database create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --name "cosmicworks"
    
  4. 使用指令 az cosmosdb gremlin graph create 來建立名為 的新圖形 products

    az cosmosdb gremlin graph create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --database-name "cosmicworks" \
        --name "products" \
        --partition-key-path "/category"
    

取得認證

現在,取得客戶端程式庫所需的密碼,以建立與最近創建的帳戶的連接。

  1. 使用 az cosmosdb show 來取得帳戶的主機。

    az cosmosdb show \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --query "{host:name}"
    
  2. 記錄先前命令輸出中屬性 host 的值。 此屬性的值是您稍後在本指南中用來連線到具有程式庫的帳戶的主機

  3. 使用 az cosmosdb keys list 可獲得帳戶的 金鑰

    az cosmosdb keys list \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --type "keys"
    
  4. 記錄先前命令輸出中屬性 primaryMasterKey 的值。 此屬性的值是您在本指南稍後用來使用程式庫連接至帳戶的 金鑰

準備開發環境

然後,使用新專案和用戶端程式庫來設定您的開發環境。 此步驟是繼續本指南其餘部分之前的最後一個必要先決條件。

  1. 從空白資料夾中開始。

  2. 將新的模組初始化。

    npm init es6 --yes
    
  3. 從 Node Package Manager npm 安裝 gremlin 套件。

    npm install --save gremlin
    
  4. 建立 index.js 檔案。

  1. 從空白資料夾中開始。

  2. 將新的模組初始化。

    npm init es6 --yes
    
  3. 從 Node Package Manager npm 安裝 typescript 套件。

    npm install --save-dev typescript
    
  4. 在 npm 安裝 tsx 套件。

    npm install --save-dev tsx
    
  5. 在 npm 安裝 gremlin 套件。

    npm install --save gremlin
    
  6. 在 npm 安裝 @types/node 套件。

    npm install --save-dev @types/node
    
  7. 在 npm 安裝 @types/gremlin 套件。

    npm install --save-dev @types/gremlin
    
  8. 使用編譯程式 (tsc) 初始化 TypeScript 專案。

    npx tsc --init --target es2017 --module es2022 --moduleResolution nodenext
    
  9. 建立 index.ts 檔案。

物件模型

說明
DriverRemoteConnection 代表與 Gremlin 伺服器的連線
GraphTraversalSource 用來建構和執行 Gremlin 周遊

程式碼範例

驗證用戶端

首先,使用本指南稍早收集的認證來驗證用戶端。

  1. 在整合開發環境 (IDE) 中開啟 index.js 檔案。

  2. 匯入 gremlin 套件和所需類型:

    import gremlin from 'gremlin';
    const { Client, auth } = gremlin.driver;
    const { PlainTextSaslAuthenticator } = auth;
    
  3. 為本指南稍早收集的認證建立字串變數。 將變數 hostname 命名為 primaryKey和 。

    const hostname = '<host>';
    const primaryKey = '<key>';
    
  4. 使用先前步驟中建立的認證和組態變數來建立型別 PlainTextSaslAuthenticator 物件。 將物件儲存在名為 authenticator的變數中。

    const authenticator = new PlainTextSaslAuthenticator(
        '/dbs/cosmicworks/colls/products',
        primaryKey
    );
    
  5. Client使用驗證器變數建立物件。 將變數 client命名為 。

    const client = new Client(
        `wss://${hostname}.gremlin.cosmos.azure.com:443/`,
        {
            authenticator,
            traversalsource: 'g',
            rejectUnauthorized: true,
            mimeType: 'application/vnd.gremlin-v2.0+json'
        }
    );
    
  1. 在整合開發環境中開啟 index.ts 檔案(IDE)。

  2. 匯入 gremlin 套件和所需類型:

    import gremlin from 'gremlin';
    const { Client, auth } = gremlin.driver;
    const { PlainTextSaslAuthenticator } = auth;
    
  3. 為本指南稍早收集的認證建立字串變數。 將變數 hostname 命名為 primaryKey和 。

    const hostname: string = '<host>';
    const primaryKey: string = '<key>';
    
  4. 使用先前步驟中建立的認證和組態變數來建立型別 PlainTextSaslAuthenticator 物件。 將物件儲存在名為 authenticator的變數中。

    const authenticator = new PlainTextSaslAuthenticator(
        '/dbs/cosmicworks/colls/products',
        primaryKey
    );
    
  5. Client使用驗證器變數建立物件。 將變數 client命名為 。

    const client = new Client(
        `wss://${hostname}.gremlin.cosmos.azure.com:443/`,
        {
            authenticator,
            traversalsource: 'g',
            rejectUnauthorized: true,
            mimeType: 'application/vnd.gremlin-v2.0+json'
        }
    );
    

插入數據

接下來,將新的頂點和邊緣資料插入到圖形中。 在建立新資料之前,請清除任何現有資料的圖表。

  1. 執行 g.V().drop() 查詢以清除圖形中的所有頂點和邊緣。

    await client.submit('g.V().drop()');
    
  2. 請用 Gremlin 查詢來新增一個頂點。

    const insert_vertex_query = `
        g.addV('product')
            .property('id', prop_id)
            .property('name', prop_name)
            .property('category', prop_category)
            .property('quantity', prop_quantity)
            .property('price', prop_price)
            .property('clearance', prop_clearance)
    `;
    
  3. 為單一產品新增一個頂點。

    await client.submit(insert_vertex_query, {
        prop_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
        prop_name: 'Yamba Surfboard',
        prop_category: 'gear-surf-surfboards',
        prop_quantity: 12,
        prop_price: 850.00,
        prop_clearance: false,
    });
    
  4. 再新增兩個頂點,即可獲得兩個額外的產品。

    await client.submit(insert_vertex_query, {
        prop_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc',
        prop_name: 'Montau Turtle Surfboard',
        prop_category: 'gear-surf-surfboards',
        prop_quantity: 5,
        prop_price: 600.00,
        prop_clearance: true,
    });
    
    await client.submit(insert_vertex_query, {
        prop_id: 'cccccccc-2222-3333-4444-dddddddddddd',
        prop_name: 'Noosa Surfboard',
        prop_category: 'gear-surf-surfboards',
        prop_quantity: 31,
        prop_price: 1100.00,
        prop_clearance: false,
    });
    
  5. 建立另一個新增邊緣的 Gremlin 查詢。

    const insert_edge_query = `
        g.V([prop_partition_key, prop_source_id])
            .addE('replaces')
            .to(g.V([prop_partition_key, prop_target_id]))
    `;
    
  6. 新增兩個邊緣。

    await client.submit(insert_edge_query, {
        prop_partition_key: 'gear-surf-surfboards',
        prop_source_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc',
        prop_target_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
    });
    
    await client.submit(insert_edge_query, {
        prop_partition_key: 'gear-surf-surfboards',
        prop_source_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc',
        prop_target_id: 'cccccccc-2222-3333-4444-dddddddddddd',
    });
    
  1. 執行 g.V().drop() 查詢以清除圖形中的所有頂點和邊緣。

    await client.submit('g.V().drop()');
    
  2. 請用 Gremlin 查詢來新增一個頂點。

    const insert_vertex_query: string = `
        g.addV('product')
            .property('id', prop_id)
            .property('name', prop_name)
            .property('category', prop_category)
            .property('quantity', prop_quantity)
            .property('price', prop_price)
            .property('clearance', prop_clearance)
    `;
    
  3. 為單一產品新增一個頂點。

    await client.submit(insert_vertex_query, {
        prop_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
        prop_name: 'Yamba Surfboard',
        prop_category: 'gear-surf-surfboards',
        prop_quantity: 12,
        prop_price: 850.00,
        prop_clearance: false,
    });
    
  4. 再新增兩個頂點,即可獲得兩個額外的產品。

    await client.submit(insert_vertex_query, {
        prop_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc',
        prop_name: 'Montau Turtle Surfboard',
        prop_category: 'gear-surf-surfboards',
        prop_quantity: 5,
        prop_price: 600.00,
        prop_clearance: true,
    });
    
    await client.submit(insert_vertex_query, {
        prop_id: 'cccccccc-2222-3333-4444-dddddddddddd',
        prop_name: 'Noosa Surfboard',
        prop_category: 'gear-surf-surfboards',
        prop_quantity: 31,
        prop_price: 1100.00,
        prop_clearance: false,
    });
    
  5. 建立另一個新增邊緣的 Gremlin 查詢。

    const insert_edge_query: string = `
        g.V([prop_partition_key, prop_source_id])
            .addE('replaces')
            .to(g.V([prop_partition_key, prop_target_id]))
    `;
    
  6. 新增兩個邊緣。

    await client.submit(insert_edge_query, {
        prop_partition_key: 'gear-surf-surfboards',
        prop_source_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc',
        prop_target_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
    });
    
    await client.submit(insert_edge_query, {
        prop_partition_key: 'gear-surf-surfboards',
        prop_source_id: 'bbbbbbbb-1111-2222-3333-cccccccccccc',
        prop_target_id: 'cccccccc-2222-3333-4444-dddddddddddd',
    });
    

讀取資料

然後,讀取先前插入圖表的資料。

  1. 使用唯一識別碼及分區鍵創建一個查詢以讀取頂點。

    const read_vertex_query = 'g.V([prop_partition_key, prop_id])';
    
  2. 然後,透過提供必要的參數來讀取頂點。

    let read_results = await client.submit(read_vertex_query, {
        prop_partition_key: 'gear-surf-surfboards',
        prop_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
    });
    
    let matched_item = read_results._items[0];
    
  1. 使用唯一識別碼及分區鍵創建一個查詢以讀取頂點。

    const read_vertex_query: string = 'g.V([prop_partition_key, prop_id])';
    
  2. 然後,透過提供必要的參數來讀取頂點。

    let read_results = await client.submit(read_vertex_query, {
        prop_partition_key: 'gear-surf-surfboards',
        prop_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
    });
    
    let matched_item = read_results._items[0];
    

查詢數據

最後,使用查詢來尋找與圖形中特定遍歷或篩選器相符的所有資料。

  1. 建立查詢,以尋找從特定頂點周遊的所有頂點。

    const find_vertices_query = `
        g.V().hasLabel('product')
            .has('category', prop_partition_key)
            .has('name', prop_name)
            .outE('replaces').inV()
    `;
    
  2. 執行指定 Montau Turtle Surfboard 產品的查詢。

    let find_results = await client.submit(find_vertices_query, {
        prop_partition_key: 'gear-surf-surfboards',
        prop_name: 'Montau Turtle Surfboard',
    });
    
  3. 逐一查看查詢結果。

    for (const item of find_results._items) {
        // Do something here with each result
    }
    
  1. 建立查詢,以尋找從特定頂點周遊的所有頂點。

    const find_vertices_query: string = `
        g.V().hasLabel('product')
            .has('category', prop_partition_key)
            .has('name', prop_name)
            .outE('replaces').inV()
    `;
    
  2. 執行指定 Montau Turtle Surfboard 產品的查詢。

    let find_results = await client.submit(find_vertices_query, {
        prop_partition_key: 'gear-surf-surfboards',
        prop_name: 'Montau Turtle Surfboard',
    });
    
  3. 逐一查看查詢結果。

    for (const item of find_results._items) {
        // Do something here with each result
    }
    

執行程式碼

使用應用程式目錄中的終端機執行新建立的應用程式。

node index.js
npx tsx index.ts

清除資源

當您不再需要帳戶時,請從 Azure 訂用帳戶中移除帳戶,方法是 刪除 該資源。

az cosmosdb delete \
    --resource-group "<resource-group-name>" \
    --name "<account-name>"