クイック スタート: Node.js用 Apache Gremlin クライアント ライブラリのAzure Cosmos DB

Important

99.999% 可用性サービス レベル アグリーメント (SLA)、インスタント 自動スケール、および複数のリージョン間の自動フェールオーバーを使用した 大規模 なシナリオ向けのデータベース ソリューションをお探しですか? NoSQL 向けの Azure Cosmos DB を検討してください。

オンライン分析処理 (OLAP) グラフを実装するか、既存の Apache Gremlin アプリケーションを移行しますか? Microsoft Fabric のGraph を検討する。

非構造化データの格納、管理、クエリを Node.js するための Apache Gremlin クライアント ライブラリのAzure Cosmos DBを開始します。 このガイドの手順に従って、新しいアカウントの作成、Node.js クライアント ライブラリのインストール、アカウントへの接続、一般的な操作の実行、最終的なサンプル データのクエリを実行します。

ライブラリのソース コード | パッケージ (npm)

前提条件

  • Azure サブスクリプション

    • Azure サブスクリプションがない場合は、開始する前に free アカウントを作成します。
  • Azure Cloud ShellAzure CLIの最新バージョン。

    • CLI 参照コマンドをローカルで実行する場合は、az login コマンドを使用してAzure CLIにサインインします。
  • Node.js 22 以降

設定

まず、このガイドのアカウントと開発環境を設定します。 このセクションでは、アカウントの作成、資格情報の取得、開発環境の準備のプロセスについて説明します。

アカウントを作成する

まず、Apache Gremlin アカウント用の API を作成します。 アカウントが作成されたら、データベースとグラフ リソースを作成します。

  1. ターゲット リソース グループがまだない場合は、 az group create コマンドを使用して、サブスクリプションに新しいリソース グループを作成します。

    az group create \
        --name "<resource-group-name>" \
        --location "<location>"
    
  2. az cosmosdb create コマンドを使用して、Apache Gremlin アカウントの新しいAzure Cosmos DBを既定の設定で作成します。

    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 パッケージ マネージャー (npm) から gremlin パッケージをインストールします。

    npm install --save gremlin
    
  4. index.js ファイルを作成します。

  1. 空のフォルダーから開始します。

  2. 新しいモジュールを初期化します。

    npm init es6 --yes
    
  3. Node パッケージ マネージャー (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. このガイドで前に収集した資格情報の文字列変数を作成します。 変数に hostnameprimaryKeyという名前を付けます。

    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. 統合開発環境 (IDE) で index.ts ファイルを開きます。

  2. gremlin パッケージと必要な種類をインポートします。

    import gremlin from 'gremlin';
    const { Client, auth } = gremlin.driver;
    const { PlainTextSaslAuthenticator } = auth;
    
  3. このガイドで前に収集した資格情報の文字列変数を作成します。 変数に hostnameprimaryKeyという名前を付けます。

    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. 1 つの製品に頂点を追加します。

    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. 2つの追加製品に対応する2つの頂点を追加します。

    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. 2 つのエッジを追加します。

    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. 1 つの製品に頂点を追加します。

    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. 2つの追加製品に対応する2つの頂点を追加します。

    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. 2 つのエッジを追加します。

    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>"