ルーティンを作成する

既存のデータセット内にルーティンを作成します。

コードサンプル

Go

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートGo の手順に沿って設定を行ってください。詳細については、BigQuery Go API のリファレンス ドキュメントをご覧ください。

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/bigquery"
)

// createRoutine demonstrates creating a new BigQuery UDF using the routine API.
func createRoutine(projectID, datasetID, routineID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydatasetid"
	// routineID := "myroutineid"
	ctx := context.Background()

	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	metaData := &bigquery.RoutineMetadata{
		Type:     "SCALAR_FUNCTION",
		Language: "SQL",
		Body:     "x * 3",
		Arguments: []*bigquery.RoutineArgument{
			{Name: "x", DataType: &bigquery.StandardSQLDataType{TypeKind: "INT64"}},
		},
	}

	routineRef := client.Dataset(datasetID).Routine(routineID)
	if err := routineRef.Create(ctx, metaData); err != nil {
		return err
	}
	return nil
}

Java

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートJava の手順に沿って設定を行ってください。詳細については、BigQuery Java API のリファレンス ドキュメントをご覧ください。

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

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.RoutineArgument;
import com.google.cloud.bigquery.RoutineId;
import com.google.cloud.bigquery.RoutineInfo;
import com.google.cloud.bigquery.StandardSQLDataType;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.common.collect.ImmutableList;

// Sample to create a routine
public class CreateRoutine {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String routineName = "MY_ROUTINE_NAME";
    createRoutine(datasetName, routineName);
  }

  public static void createRoutine(String datasetName, String routineName) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      RoutineId routineId = RoutineId.of(datasetName, routineName);

      RoutineInfo routineInfo =
          RoutineInfo.newBuilder(routineId)
              .setRoutineType("SCALAR_FUNCTION")
              .setLanguage("SQL")
              .setBody("x * 3")
              .setArguments(
                  ImmutableList.of(
                      RoutineArgument.newBuilder()
                          .setName("x")
                          .setDataType(
                              StandardSQLDataType.newBuilder(StandardSQLTypeName.INT64).build())
                          .build()))
              .build();
      bigquery.create(routineInfo);
      System.out.println("Routine created successfully");
    } catch (BigQueryException e) {
      System.out.println("Routine was not created. \n" + e.toString());
    }
  }
}

Node.js

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

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

// Import the Google Cloud client library and create a client
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function createRoutine() {
  // Creates a new routine named "my_routine" in "my_dataset".

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = 'my_dataset';
  // const routineId = 'my_routine';

  const dataset = bigquery.dataset(datasetId);

  // Create routine reference
  let routine = dataset.routine(routineId);

  const config = {
    arguments: [
      {
        name: 'x',
        dataType: {
          typeKind: 'INT64',
        },
      },
    ],
    definitionBody: 'x * 3',
    routineType: 'SCALAR_FUNCTION',
    returnType: {
      typeKind: 'INT64',
    },
  };

  // Make API call
  [routine] = await routine.create(config);

  console.log(`Routine ${routineId} created.`);
}
createRoutine();

Python

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートPython の手順に沿って設定を行ってください。詳細については、BigQuery Python API のリファレンス ドキュメントをご覧ください。

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

from google.cloud import bigquery

# Construct a BigQuery client object.
client = bigquery.Client()

# TODO(developer): Choose a fully qualified ID for the routine.
# routine_id = "my-project.my_dataset.my_routine"

routine = bigquery.Routine(
    routine_id,
    type_="SCALAR_FUNCTION",
    language="SQL",
    body="x * 3",
    arguments=[
        bigquery.RoutineArgument(
            name="x",
            data_type=bigquery.StandardSqlDataType(
                type_kind=bigquery.StandardSqlTypeNames.INT64
            ),
        )
    ],
)

routine = client.create_routine(routine)  # Make an API request.

print("Created routine {}".format(routine.reference))

次のステップ

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