セッションを作成する(v1)

新しい Dataproc セッションを作成します。

コードサンプル

Node.js

このサンプルを試す前に、クライアント ライブラリを使用した Managed Service for Apache Spark のクイックスタートにある Node.js の設定手順を完了してください。詳細については、Managed Service for Apache Spark Node.js API のリファレンス ドキュメントをご覧ください。

Managed Service for Apache Spark に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

'use strict';

const {SessionControllerClient} = require('@google-cloud/dataproc');
const {status} = require('@grpc/grpc-js');

/**
 * Creates a Dataproc session.
 *
 * @param {string} sessionId - The caller-chosen ID to use for the session, which becomes the final component of the session's resource name. Must be 4-63 characters containing lowercase letters, numbers, and hyphens.
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Dataproc location (region) where the session is created (for example, 'us-central1').
 */
async function createSession(sessionId, projectId, locationId) {
  // Dataproc is a regional service requiring the regional API endpoint.
  const client = new SessionControllerClient({
    apiEndpoint: `${locationId}-dataproc.googleapis.com`,
  });

  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const session = {
      jupyterSession: {
        kernel: 'PYTHON',
      },
    };

    const request = {
      parent,
      session,
      sessionId,
    };

    // Dataproc session creation is a long-running operation.
    const [operation] = await client.createSession(request);
    const [response] = await operation.promise();

    console.log(`Created session: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Session already exists: ${err.message}`);
    } else if (err.code) {
      console.error(`Google API error (${err.code}): ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { createSession };

次のステップ

他の Google Cloud プロダクトのコードサンプルを検索およびフィルタするには、Google Cloud サンプル ブラウザをご覧ください。