Databricks ユーティリティ (dbutils) リファレンス

この記事は、Databricks ユーティリティ (dbutils) のリファレンスです。 dbutils ユーティリティは、Python、R、および Scala ノートブックで使用できます。 ユーティリティを使用すると、次のことができます。

  • ファイルとオブジェクトストレージを効率的に操作します。

  • シークレットを操作します。

方法: ユーティリティの一覧表示、コマンド の一覧表示コマンド ヘルプの表示

ユーティリティ: 資格情報データfsジョブ 、ライブラリ、 ノートブック 、シークレットウィジェットユーティリティ API ライブラリ

利用可能なユーティリティを一覧表示する

利用可能なユーティリティと各ユーティリティの簡単な説明を一覧表示するには、PythonまたはScalaの場合は dbutils.help() を実行します。

この例では、Databricksユーティリティで使用可能なコマンドを一覧表示します。

dbutils.help()
dbutils.help()
This module provides various utilities for users to interact with the rest of Databricks.

credentials: DatabricksCredentialUtils -> Utilities for interacting with credentials within notebooks
data: DataUtils -> Utilities for understanding and interacting with datasets (EXPERIMENTAL)
fs: DbfsUtils -> Manipulates the Databricks filesystem (DBFS) from the console
jobs: JobsUtils -> Utilities for leveraging jobs features
library: LibraryUtils -> Utilities for session isolated libraries
meta: MetaUtils -> Methods to hook into the compiler (EXPERIMENTAL)
notebook: NotebookUtils -> Utilities for the control flow of a notebook (EXPERIMENTAL)
preview: Preview -> Utilities under preview category
secrets: SecretUtils -> Provides utilities for leveraging secrets within notebooks
widgets: WidgetsUtils -> Methods to create and get bound value of input widgets inside notebooks

ユーティリティで使用可能なコマンドの一覧表示

ユーティリティで使用可能なコマンドと各コマンドの簡単な説明を一覧表示するには、ユーティリティのプログラム名の後に .help() を実行します。

この例では、Databricks File System(DBFS)ユーティリティで使用可能なコマンドを一覧表示します。

dbutils.fs.help()
dbutils.fs.help()
dbutils.fs.help()
dbutils.fs provides utilities for working with FileSystems. Most methods in this package can take either a DBFS path (e.g., "/foo" or "dbfs:/foo"), or another FileSystem URI. For more info about a method, use dbutils.fs.help("methodName"). In notebooks, you can also use the %fs shorthand to access DBFS. The %fs shorthand maps straightforwardly onto dbutils calls. For example, "%fs head --maxBytes=10000 /file/path" translates into "dbutils.fs.head("/file/path", maxBytes = 10000)".

fsutils

cp(from: String, to: String, recurse: boolean = false): boolean -> Copies a file or directory, possibly across FileSystems
head(file: String, maxBytes: int = 65536): String -> Returns up to the first 'maxBytes' bytes of the given file as a String encoded in UTF-8
ls(dir: String): Seq -> Lists the contents of a directory
mkdirs(dir: String): boolean -> Creates the given directory if it does not exist, also creating any necessary parent directories
mv(from: String, to: String, recurse: boolean = false): boolean -> Moves a file or directory, possibly across FileSystems
put(file: String, contents: String, overwrite: boolean = false): boolean -> Writes the given String out to a file, encoded in UTF-8
rm(dir: String, recurse: boolean = false): boolean -> Removes a file or directory

mount

mount(source: String, mountPoint: String, encryptionType: String = "", owner: String = null, extraConfigs: Map = Map.empty[String, String]): boolean -> Mounts the given source directory into DBFS at the given mount point
mounts: Seq -> Displays information about what is mounted within DBFS
refreshMounts: boolean -> Forces all machines in this cluster to refresh their mount cache, ensuring they receive the most recent information
unmount(mountPoint: String): boolean -> Deletes a DBFS mount point
updateMount(source: String, mountPoint: String, encryptionType: String = "", owner: String = null, extraConfigs: Map = Map.empty[String, String]): boolean -> Similar to mount(), but updates an existing mount point instead of creating a new one

コマンドのヘルプを表示する

コマンドのヘルプを表示するには、コマンド名の後に .help("<command-name>") を実行します。

この例では、DBFSのコピー・コマンドのヘルプを表示します。

dbutils.fs.help("cp")
dbutils.fs.help("cp")
dbutils.fs.help("cp")
/**
* Copies a file or directory, possibly across FileSystems.
*
* Example: cp("/mnt/my-folder/a", "dbfs:/a/b")
*
* @param from FileSystem URI of the source file or directory
* @param to FileSystem URI of the destination file or directory
* @param recurse if true, all files and directories will be recursively copied
* @return true if all files were successfully copied
*/
cp(from: java.lang.String, to: java.lang.String, recurse: boolean = false): boolean

資格情報ユーティリティ(dbutils.credentials)

コマンド: assumeRole, showCurrentRole, showRoles

資格情報ユーティリティを使用すると、ノートブック内で資格情報を操作できます。このユーティリティは、 資格情報パススルーが有効になっているクラスターでのみ使用できます。使用可能なコマンドを一覧表示するには、dbutils.credentials.help() を実行します。

assumeRole(role: String): boolean -> Sets the role ARN to assume when looking for credentials to authenticate with S3
showCurrentRole: List -> Shows the currently set role
showRoles: List -> Shows the set of possible assumed roles

assignRoleコマンド(dbutils.credentials.assumeRole)

Amazon S3 で認証するための資格情報を探す際にAWS Identity and Access Management(IAM)ロールが引き受けるAmazon リソースネーム(ARN)を設定します。このコマンドを実行すると、 sc.textFile("s3a://my-bucket/my-file.csv") などの S3 アクセスコマンドを実行してオブジェクトにアクセスできます。

このコマンドのヘルプを表示するには、dbutils.credentials.help("assumeRole")を実行します。

dbutils.credentials.assumeRole("arn:aws:iam::123456789012:roles/my-role")

# Out[1]: True
dbutils.credentials.assumeRole("arn:aws:iam::123456789012:roles/my-role")

# TRUE
dbutils.credentials.assumeRole("arn:aws:iam::123456789012:roles/my-role")

// res0: Boolean = true

showCurrentRoleコマンド(dbutils.credentials.showCurrentRole)

現在設定されているAWS Identity and Access Management(IAM)ロールを一覧表示します。

このコマンドのヘルプを表示するには、dbutils.credentials.help("showCurrentRole")を実行します。

dbutils.credentials.showCurrentRole()

# Out[1]: ['arn:aws:iam::123456789012:role/my-role-a']
dbutils.credentials.showCurrentRole()

# [[1]]
# [1] "arn:aws:iam::123456789012:role/my-role-a"
dbutils.credentials.showCurrentRole()

// res0: java.util.List[String] = [arn:aws:iam::123456789012:role/my-role-a]

showRolesコマンド(dbutils.credentials.showRoles)

想定されるAWS Identity and Access Management(IAM)ロールのセットをリストします。

このコマンドのヘルプを表示するには、dbutils.credentials.help("showRoles")を実行します。

dbutils.credentials.showRoles()

# Out[1]: ['arn:aws:iam::123456789012:role/my-role-a', 'arn:aws:iam::123456789012:role/my-role-b']
dbutils.credentials.showRoles()

# [[1]]
# [1] "arn:aws:iam::123456789012:role/my-role-a"
#
# [[2]]
# [1] "arn:aws:iam::123456789012:role/my-role-b"
dbutils.credentials.showRoles()

// res0: java.util.List[String] = [arn:aws:iam::123456789012:role/my-role-a, arn:aws:iam::123456789012:role/my-role-b]

データ・ユーティリティ (dbutils.data)

プレビュー

この機能はパブリックプレビュー段階です。

注:

Databricks Runtime 9.0以降で利用可能です。

コマンド: まとめ

データ・ユーティリティを使用すると、データセットを理解して解釈できます。使用可能なコマンドを一覧表示するには、dbutils.data.help() を実行します。

dbutils.data provides utilities for understanding and interpreting datasets. This module is currently in preview and may be unstable. For more info about a method, use dbutils.data.help("methodName").

summarize(df: Object, precise: boolean): void -> Summarize a Spark DataFrame and visualize the statistics to get quick insights

要約コマンド(dbutils.data.summarize)

Apache Spark DataFrameまたはpandas DataFrameの概要統計を計算して表示します。このコマンドは、Python、Scala、Rで使用できます。

注意

このコマンドは、DataFrame の完全な内容を分析します。 非常に大きな DataFrames に対してこのコマンドを実行すると、非常にコストがかかる可能性があります。

このコマンドのヘルプを表示するには、dbutils.data.help("summarize")を実行します。

Databricks Runtime 10.4 LTS以降では、追加の precise 引数を使用して、コンピュート統計の精度を調整できます。

注:

この機能はパブリックプレビュー段階です。

  • precise がfalse(デフォルト)に設定されている場合、返される統計の一部には、実行時間を短縮するための近似値が含まれます。

    • カテゴリ列の異なる値の数には、カーディナリティの高い列の場合、最大5%の相対誤差が生じる可能性があります。

    • 異なる値の数が10000を超える場合、頻繁に発生する値のカウントには最大 0.01%の誤差が生じる可能性があります。

    • ヒストグラムとパーセンタイルの推定値には、行の総数に対して最大0.01%の誤差が生じる場合があります。

  • precise がtrueに設定されている場合、統計はより高い精度で計算されます。数値列のヒストグラムとパーセンタイルを除くすべての統計は正確な値になりました。

    • ヒストグラムとパーセンタイルの推定値には、行の総数に対して最大0.0001%の誤差が生じる場合があります。

データ概要出力の上部にあるツールチップは、現在の実行モードを示します。

この例では、デフォルトで有効になっている近似を使用して、Apache Spark DataFrameの概要統計を表示します。結果を見るには、ノートブックで次のコマンドを実行します。この例は、サンプル・データセットに基づいています。

df = spark.read.format('csv').load(
  '/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv',
  header=True,
  inferSchema=True
)
dbutils.data.summarize(df)
df <- read.df("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv", source = "csv", header="true", inferSchema = "true")
dbutils.data.summarize(df)
val df = spark.read.format("csv")
  .option("inferSchema", "true")
  .option("header", "true")
  .load("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv")
dbutils.data.summarize(df)

視覚化では、0.01より小さい数値や10000より大きい数値を簡潔に表示するためにSI 表記 を使用している点にご注意ください。例として、数値 1.25e-151.25f と表示されます。ただし、1つ例外があります。視覚化では、「G」の代わりに「B」が 1.0e9giga)に使われます。

ファイルシステム・ユーティリティ(dbutils.fs)

警告:

すべての dbutils.fs メソッドのPython実装では、キーワードの形式に camelCase ではなくsnake_case が使われます。

例えば、dbutils.fs.help() では dbutils.fs.mount()extraConfigs のオプションが表示されますが、Pythonでは extra_configs のキーワードを使います。

コマンド: cp, head, ls, mkdirs, mount, mounts, mv, put, refreshMounts, rm, アンマウント, updateMount

ファイルシステム・ユーティリティを使用すると、Databricksファイルシステム(DBFS)とはにアクセスできます。これにより、Databricksをファイルシステムとして簡単に使用できるようになります。使用可能なコマンドを一覧表示するには、dbutils.fs.help() を実行します。

dbutils.fs provides utilities for working with FileSystems. Most methods in this package can take either a DBFS path (e.g., "/foo" or "dbfs:/foo"), or another FileSystem URI. For more info about a method, use dbutils.fs.help("methodName"). In notebooks, you can also use the %fs shorthand to access DBFS. The %fs shorthand maps straightforwardly onto dbutils calls. For example, "%fs head --maxBytes=10000 /file/path" translates into "dbutils.fs.head("/file/path", maxBytes = 10000)".

fsutils

cp(from: String, to: String, recurse: boolean = false): boolean -> Copies a file or directory, possibly across FileSystems
head(file: String, maxBytes: int = 65536): String -> Returns up to the first 'maxBytes' bytes of the given file as a String encoded in UTF-8
ls(dir: String): Seq -> Lists the contents of a directory
mkdirs(dir: String): boolean -> Creates the given directory if it does not exist, also creating any necessary parent directories
mv(from: String, to: String, recurse: boolean = false): boolean -> Moves a file or directory, possibly across FileSystems
put(file: String, contents: String, overwrite: boolean = false): boolean -> Writes the given String out to a file, encoded in UTF-8
rm(dir: String, recurse: boolean = false): boolean -> Removes a file or directory

mount

mount(source: String, mountPoint: String, encryptionType: String = "", owner: String = null, extraConfigs: Map = Map.empty[String, String]): boolean -> Mounts the given source directory into DBFS at the given mount point
mounts: Seq -> Displays information about what is mounted within DBFS
refreshMounts: boolean -> Forces all machines in this cluster to refresh their mount cache, ensuring they receive the most recent information
unmount(mountPoint: String): boolean -> Deletes a DBFS mount point
updateMount(source: String, mountPoint: String, encryptionType: String = "", owner: String = null, extraConfigs: Map = Map.empty[String, String]): boolean -> Similar to mount(), but updates an existing mount point instead of creating a new one

cpコマンド(dbutils.fs.cp)

ファイルまたはディレクトリを、場合によってはファイルシステム間でコピーします。

このコマンドのヘルプを表示するには、dbutils.fs.help("cp")を実行します。

この例では、old_file.txt という名前のファイルを /FileStore から /tmp/new へコピーし、コピーされたファイルの名前を new_file.txt へ変更します。

dbutils.fs.cp("/FileStore/old_file.txt", "/tmp/new/new_file.txt")

# Out[4]: True
dbutils.fs.cp("/FileStore/old_file.txt", "/tmp/new/new_file.txt")

# [1] TRUE
dbutils.fs.cp("/FileStore/old_file.txt", "/tmp/new/new_file.txt")

// res3: Boolean = true

headコマンド(dbutils.fs.head)

ファイルに対し、指定された最大バイト数まで返します。バイトはUTF-8でエンコードされた文字列として返されます。

このコマンドのヘルプを表示するには、dbutils.fs.help("head")を実行します。

この例では、 /tmp にあるファイル: my_file.txt の最初の25バイトを表示しています。

dbutils.fs.head("/tmp/my_file.txt", 25)

# [Truncated to first 25 bytes]
# Out[12]: 'Apache Spark is awesome!\n'
dbutils.fs.head("/tmp/my_file.txt", 25)

# [1] "Apache Spark is awesome!\n"
dbutils.fs.head("/tmp/my_file.txt", 25)

// [Truncated to first 25 bytes]
// res4: String =
// "Apache Spark is awesome!
// "

lsコマンド(dbutils.fs.ls)

ディレクトリの内容を一覧表示します。

このコマンドのヘルプを表示するには、dbutils.fs.help("ls")を実行します。

この例では、 /tmpの内容に関する情報を表示します。 modificationTimeフィールドは、Databricks Runtime 10.4 LTS 以降で使用できます。 Rでは、 modificationTime文字列として返されます。

dbutils.fs.ls("/tmp")

# Out[13]: [FileInfo(path='dbfs:/tmp/my_file.txt', name='my_file.txt', size=40, modificationTime=1622054945000)]
dbutils.fs.ls("/tmp")

# For prettier results from dbutils.fs.ls(<dir>), please use `%fs ls <dir>`

# [[1]]
# [[1]]$path
# [1] "dbfs:/tmp/my_file.txt"

# [[1]]$name
# [1] "my_file.txt"

# [[1]]$size
# [1] 40

# [[1]]$isDir
# [1] FALSE

# [[1]]$isFile
# [1] TRUE

# [[1]]$modificationTime
# [1] "1622054945000"
dbutils.fs.ls("/tmp")

// res6: Seq[com.databricks.backend.daemon.dbutils.FileInfo] = WrappedArray(FileInfo(dbfs:/tmp/my_file.txt, my_file.txt, 40, 1622054945000))

mkdirsコマンド(dbutils.fs.mkdirs)

指定されたディレクトリが存在しない場合は作成します。また、必要な親ディレクトリも作成します。

このコマンドのヘルプを表示するには、dbutils.fs.help("mkdirs")を実行します。

この例では /tmp の中に /parent/child/grandchild のディレクトリ構造を作成しています。

dbutils.fs.mkdirs("/tmp/parent/child/grandchild")

# Out[15]: True
dbutils.fs.mkdirs("/tmp/parent/child/grandchild")

# [1] TRUE
dbutils.fs.mkdirs("/tmp/parent/child/grandchild")

// res7: Boolean = true

mountコマンド(dbutils.fs.mount)

指定されたソースディレクトリを、指定されたマウントポイントのDBFSにマウントします。

このコマンドのヘルプを表示するには、dbutils.fs.help("mount")を実行します。

aws_bucket_name = "my-bucket"
mount_name = "s3-my-bucket"

dbutils.fs.mount("s3a://%s" % aws_bucket_name, "/mnt/%s" % mount_name)
val AwsBucketName = "my-bucket"
val MountName = "s3-my-bucket"

dbutils.fs.mount(s"s3a://$AwsBucketName", s"/mnt/$MountName")

その他のコード例については、「Amazon S3 に接続する」を参照してください。

mountsコマンド(dbutils.fs.mounts)

DBFS 内に現在マウントされているものに関する情報を表示します。

このコマンドのヘルプを表示するには、dbutils.fs.help("mounts")を実行します。

警告:

他のすべての稼働中のクラスターで dbutils.fs.refreshMounts() を呼び出して、新しいマウントを伝達します。 refreshMounts コマンド (dbutils.fs.refreshMounts)を参照してください。

dbutils.fs.mounts()

# Out[11]: [MountInfo(mountPoint='/mnt/databricks-results', source='databricks-results', encryptionType='sse-s3')]
dbutils.fs.mounts()

その他のコード例については、「Amazon S3 に接続する」を参照してください。

mvコマンド(dbutils.fs.mv)

ファイルまたはディレクトリを、場合によってはファイルシステム間で移動します。ファイルシステム内での移動の場合でも、コピーの後に削除が行われます。

このコマンドのヘルプを表示するには、dbutils.fs.help("mv")を実行します。

この例では、ファイル my_file.txt/FileStore から /tmp/parent/child/granchild に移動します。

dbutils.fs.mv("/FileStore/my_file.txt", "/tmp/parent/child/grandchild")

# Out[2]: True
dbutils.fs.mv("/FileStore/my_file.txt", "/tmp/parent/child/grandchild")

# [1] TRUE
dbutils.fs.mv("/FileStore/my_file.txt", "/tmp/parent/child/grandchild")

// res1: Boolean = true

putコマンド(dbutils.fs.put)

指定された文字列をファイルに書き込みます。文字列はUTF-8でエンコードされています。

このコマンドのヘルプを表示するには、dbutils.fs.help("put")を実行します。

この例では、Hello, Databricks! という文字列を /tmp 内の hello_db.txt という名前のファイルに書き込みます。ファイルがすでに存在する場合は、上書きされます。

dbutils.fs.put("/tmp/hello_db.txt", "Hello, Databricks!", True)

# Wrote 18 bytes.
# Out[6]: True
dbutils.fs.put("/tmp/hello_db.txt", "Hello, Databricks!", TRUE)

# [1] TRUE
dbutils.fs.put("/tmp/hello_db.txt", "Hello, Databricks!", true)

// Wrote 18 bytes.
// res2: Boolean = true

refreshMountsコマンド(dbutils.fs.refreshMounts)

クラスター内のすべてのマシンにマウントキャッシュを強制的に更新させ、最新の情報を確実に受信できるようにします。

このコマンドのヘルプを表示するには、dbutils.fs.help("refreshMounts")を実行します。

dbutils.fs.refreshMounts()
dbutils.fs.refreshMounts()

その他のコード例については、「Amazon S3 に接続する」を参照してください。

rmコマンド(dbutils.fs.rm)

ファイルまたはディレクトリを削除し、必要に応じてその内容をすべて削除します。 ファイルが指定されている場合、recurse パラメーターは無視されます。 ディレクトリが指定されている場合、再帰が無効になっていて、ディレクトリが空でない場合、エラーが発生します。

このコマンドのヘルプを表示するには、dbutils.fs.help("rm")を実行します。

この例では、ディレクトリの内容を含むディレクトリ /tmp を削除します。

dbutils.fs.rm("/tmp", True)

# Out[8]: True
dbutils.fs.rm("/tmp", TRUE)

# [1] TRUE
dbutils.fs.rm("/tmp", true)

// res6: Boolean = true

unmountコマンド(dbutils.fs.unmount)

DBFSのマウントポイントを削除します。

警告:

エラーを回避するには、他のジョブがマウント・ポイントの読み取りまたは書き込みを行っている間は、マウント・ポイントを変更しないでください。 マウントを変更した後は、必ず他のすべての稼働中のクラスターで dbutils.fs.refreshMounts() を実行して、マウントの更新を伝達します。 refreshMounts コマンド (dbutils.fs.refreshMounts)を参照してください。

このコマンドのヘルプを表示するには、dbutils.fs.help("unmount")を実行します。

dbutils.fs.unmount("/mnt/<mount-name>")

その他のコード例については、「Amazon S3 に接続する」を参照してください。

updateMountコマンド(dbutils.fs.updateMount)

dbutils.fs.mount コマンドと似ていますが、新しいマウントポイントを作成するのではなく、既存のマウントポイントを更新します。マウントポイントが存在しない場合はエラーを返します。

このコマンドのヘルプを表示するには、dbutils.fs.help("updateMount")を実行します。

警告:

エラーを回避するには、他のジョブがマウント・ポイントの読み取りまたは書き込みを行っている間は、マウント・ポイントを変更しないでください。 マウントを変更した後は、必ず他のすべての稼働中のクラスターで dbutils.fs.refreshMounts() を実行して、マウントの更新を伝達します。 refreshMounts コマンド (dbutils.fs.refreshMounts)を参照してください。

このコマンドは、Databricks Runtime 10.4 LTS 以降で使用できます。

aws_bucket_name = "my-bucket"
mount_name = "s3-my-bucket"

dbutils.fs.updateMount("s3a://%s" % aws_bucket_name, "/mnt/%s" % mount_name)
val AwsBucketName = "my-bucket"
val MountName = "s3-my-bucket"

dbutils.fs.updateMount(s"s3a://$AwsBucketName", s"/mnt/$MountName")

ジョブ・ユーティリティ(dbutils.jobs)

サブユーティリティ: タスク値

注:

このユーティリティはPythonのみで使用できます。

ジョブ・ユーティリティを使えば、ジョブの機能を活用することができます。このユーティリティのヘルプを表示するには、dbutils.jobs.help() を実行します。

Provides utilities for leveraging jobs features.

taskValues: TaskValuesUtils -> Provides utilities for leveraging job task values

taskValuesサブユーティリティ(dbutils.jobs.taskValues)

コマンド: 取得設定

注:

このサブユーティリティは、Pythonでのみ使用できます。

ジョブ・タスクの値を活用するためのコマンドを提供します。

このサブユーティリティを使用して、ジョブの実行中に任意の値を設定および取得します。これらの値は タスク値と呼ばれます。同じジョブ実行内のダウンストリーム・タスクのタスク値にアクセスできます。たとえば、実行ジョブ内の異なるタスク間で、機械学習モデルの評価に関する情報などの識別子やメトリクスを通信できます。各タスクは、複数のタスク値の設定や取得、またはその両方を行うことができます。各タスク値には、同じタスク内に一意のキーがあります。この一意のキーは、タスク値のキーと呼ばれます。タスク値には、タスク名とタスク値のキーを使用してアクセスします。

このサブユーティリティのヘルプを表示するには、 dbutils.jobs.taskValues.help() を実行します。

getコマンド(dbutils.jobs.taskValues.get)

注:

このコマンドはPythonでのみ使用できます。

Databricks Runtime 10.4以前では、 get がタスクを見つけられない場合、 ValueError の代わりにPy4JJavaErrorが発生します。

現在のジョブ実行において指定されたタスクで指定されたタスク値の内容を取得します。

このコマンドのヘルプを表示するには、dbutils.jobs.taskValues.help("get")を実行します。

例:

dbutils.jobs.taskValues.get(taskKey    = "my-task", \
                            key        = "my-key", \
                            default    = 7, \
                            debugValue = 42)

前述の例を説明します。

  • taskKey は、タスク値を設定したタスクの名前です。コマンドがこのタスクを見つけられない場合は、 ValueError が発生します。

  • key は、set コマンド (dbutils.ジョブ.taskValues.set) で設定したタスク値のキーの名前です。 コマンドがこのタスク値のキーを見つけられない場合は、 ValueError が発生します ( default が指定されていない場合)。

  • default は、 key が見つからない場合に返されるオプションの値です。defaultNone にはできません。

  • debugValue は、ジョブ外で実行されているノートブックからタスクの値を取得しようとした場合に返されるオプションの値です。デバッグ中にノートブックを手動で実行する際に、デフォルトで TypeError を発生させるのではなく何らかの値を返したい場合に便利です。debugValueNone にはできません。

ジョブの外部で実行されているノートブック内からタスク値を取得しようとすると、このコマンドはデフォルトで TypeError を発生させます。ただし、コマンドで debugValue 引数が指定されている場合は、TypeError を発生させる代わりに debugValue の値が返されます。

setコマンド(dbutils.jobs.taskValues.set)

注:

このコマンドはPythonでのみ使用できます。

タスクの値を設定または更新します。ジョブ実行には最大250のタスク値を設定できます。

このコマンドのヘルプを表示するには、dbutils.jobs.taskValues.help("set")を実行します。

例としては次のようなものがあります。

dbutils.jobs.taskValues.set(key   = "my-key", \
                            value = 5)

dbutils.jobs.taskValues.set(key   = "my-other-key", \
                            value = "my other value")

前述の例を説明します。

  • key はタスク値のキーです。このキーはタスクに一意のものでなければなりません。つまり、2 つの異なるタスクが、それぞれに K というキーを持つタスク値を設定する場合、これらは K という同じキーを持つ 2 つの異なるタスク値となります。

  • value は、このタスク値のキーの値です。このコマンドは、値を内部的にJSON形式で表現する必要があります。値のJSON表現のサイズは48 KiBを超えてはなりません。

ジョブの外部で実行されているノートブック内からタスク値を設定しようとしても、このコマンドからは何も得られません。

ライブラリ ユーティリティ (dbutils.ライブラリ)

dbutils.library サブモジュールのほとんどのメソッドは非推奨です。「ライブラリ ユーティリティ (dbutils.library) (レガシー)」を参照してください。

ローカルにインストールまたはアップグレードされたライブラリが現在の SparkSession の Python カーネルで正しく機能するように、Databricks で Python プロセスをプログラムで再起動する必要がある場合があります。 これを行うには、 dbutils.library.restartPython コマンドを実行します。 Databricksで Python プロセスを再起動するを参照してください。

ノートブック・ユーティリティ(dbutils.notebook)

コマンド: 終了実行

ノートブック・ユーティリティを使用すると、ノートブックを連結し、その結果に基づいて操作できます。Databricksノートブックを別のノートブックから実行するを参照してください。

使用可能なコマンドを一覧表示するには、dbutils.notebook.help() を実行します。

exit(value: String): void -> This method lets you exit a notebook with a value
run(path: String, timeoutSeconds: int, arguments: Map): String -> This method runs a notebook and returns its exit value.

終了コマンド(dbutils.notebook.exit)

値を持つノートブックを終了します。

このコマンドのヘルプを表示するには、dbutils.notebook.help("exit")を実行します。

この例では、Exiting from My Other Notebook という値でノートブックを終了します。

dbutils.notebook.exit("Exiting from My Other Notebook")

# Notebook exited: Exiting from My Other Notebook
dbutils.notebook.exit("Exiting from My Other Notebook")

# Notebook exited: Exiting from My Other Notebook
dbutils.notebook.exit("Exiting from My Other Notebook")

// Notebook exited: Exiting from My Other Notebook

注:

実行にバックグラウンドで実行される構造化ストリーミングを伴うクエリーがある場合、 dbutils.notebook.exit() を呼び出しても実行は終了しません。実行は、クエリーがバックグラウンドで実行されている限り続けられます。バックグラウンドで実行中のクエリーを停止するには、クエリーのセルで [キャンセル] をクリックするか、 query.stop() を実行します。クエリーが停止したら、 dbutils.notebook.exit() を使用して実行を終了できます。

runコマンド(dbutils.notebook.run)

ノートブックを実行し、その終了値を返します。デフォルトでは、ノートブックは現在のクラスターで実行されます。

注:

run コマンドから返される文字列値の最大長は5 MBです。単一のコマンド実行の出力を取得するGET /jobs/runs/get-output)を参照してください。

このコマンドのヘルプを表示するには、dbutils.notebook.help("run")を実行します。

この例では、呼び出し元のノートブックと同じ場所で My Other Notebook という名前のノートブックを実行します。呼び出されたノートブックは、dbutils.notebook.exit("Exiting from My Other Notebook") というコード行で終わります。呼び出されたノートブックの実行が60秒以内に終了しない場合、例外がスローされます。

dbutils.notebook.run("My Other Notebook", 60)

# Out[14]: 'Exiting from My Other Notebook'
dbutils.notebook.run("My Other Notebook", 60)

// res2: String = Exiting from My Other Notebook

シークレット・ユーティリティ(dbutils.secrets)

コマンド: get, getBytes, list, listScopes

secrets ユーティリティを使用すると、機密性の高い資格情報をノートブックに表示することなく、保存してアクセスできます。 「シークレット の管理 」および 「ノートブックでのシークレットの使用」を参照してください。 使用可能なコマンドを一覧表示するには、 dbutils.secrets.help()を実行します。

get(scope: String, key: String): String -> Gets the string representation of a secret value with scope and key
getBytes(scope: String, key: String): byte[] -> Gets the bytes representation of a secret value with scope and key
list(scope: String): Seq -> Lists secret metadata for secrets within a scope
listScopes: Seq -> Lists secret scopes

getコマンド(dbutils.secrets.get)

指定されたシークレットスコープとキーのシークレット値の文字列表現を取得します。

警告:

管理者、シークレット作成者、および権限を付与されたユーザーは、Databricksシークレットを読むことができます。Databricksは、ノートブックに表示される可能性のあるシークレット値を伏字処理するよう努めますが、これらのユーザーがシークレットを読むのを回避することはできません。詳細については、「シークレットの伏字処理」を参照してください。

このコマンドのヘルプを表示するには、dbutils.secrets.help("get")を実行します。

この例では、 my-scope という名前のスコープと my-keyという名前のキーのシークレット値の文字列表現を取得します。

dbutils.secrets.get(scope="my-scope", key="my-key")

# Out[14]: '[REDACTED]'
dbutils.secrets.get(scope="my-scope", key="my-key")

# [1] "[REDACTED]"
dbutils.secrets.get(scope="my-scope", key="my-key")

// res0: String = [REDACTED]

getBytesコマンド(dbutils.secrets.getBytes)

指定されたスコープとキーのシークレット値のバイト表現を取得します。

このコマンドのヘルプを表示するには、dbutils.secrets.help("getBytes")を実行します。

この例では、 my-scope という名前のスコープと my-key という名前のキーのシークレット値(この例では a1!b2@c3#)のバイト表現を取得します。

dbutils.secrets.getBytes(scope="my-scope", key="my-key")

# Out[1]: b'a1!b2@c3#'
dbutils.secrets.getBytes(scope="my-scope", key="my-key")

# [1] 61 31 21 62 32 40 63 33 23
dbutils.secrets.getBytes(scope="my-scope", key="my-key")

// res1: Array[Byte] = Array(97, 49, 33, 98, 50, 64, 99, 51, 35)

listコマンド(dbutils.secrets.list)

指定したスコープ内のシークレットのメタデータを一覧表示します。

このコマンドのヘルプを表示するには、dbutils.secrets.help("list")を実行します。

この例では、 my-scope という名前のスコープ内のシークレットのメタデータを一覧表示します。

dbutils.secrets.list("my-scope")

# Out[10]: [SecretMetadata(key='my-key')]
dbutils.secrets.list("my-scope")

# [[1]]
# [[1]]$key
# [1] "my-key"
dbutils.secrets.list("my-scope")

// res2: Seq[com.databricks.dbutils_v1.SecretMetadata] = ArrayBuffer(SecretMetadata(my-key))

listScopesコマンド(dbutils.secrets.listScopes)

利用可能なスコープを一覧表示します。

このコマンドのヘルプを表示するには、dbutils.secrets.help("listScopes")を実行します。

この例では、使用可能なスコープを一覧表示しています。

dbutils.secrets.listScopes()

# Out[14]: [SecretScope(name='my-scope')]
dbutils.secrets.listScopes()

# [[1]]
# [[1]]$name
# [1] "my-scope"
dbutils.secrets.listScopes()

// res3: Seq[com.databricks.dbutils_v1.SecretScope] = ArrayBuffer(SecretScope(my-scope))

ウィジェット・ユーティリティ(dbutils.widgets)

コマンド: コンボボックスドロップダウン取得引数の取得複数選択、削除、すべて削除テキスト

ウィジェット・ユーティリティを使用すると、ノートブックをパラメーター化できます。Databricksのウィジェットを参照してください。

使用可能なコマンドを一覧表示するには、dbutils.widgets.help() を実行します。

combobox(name: String, defaultValue: String, choices: Seq, label: String): void -> Creates a combobox input widget with a given name, default value and choices
dropdown(name: String, defaultValue: String, choices: Seq, label: String): void -> Creates a dropdown input widget a with given name, default value and choices
get(name: String): String -> Retrieves current value of an input widget
getArgument(name: String, optional: String): String -> (DEPRECATED) Equivalent to get
multiselect(name: String, defaultValue: String, choices: Seq, label: String): void -> Creates a multiselect input widget with a given name, default value and choices
remove(name: String): void -> Removes an input widget from the notebook
removeAll: void -> Removes all widgets in the notebook
text(name: String, defaultValue: String, label: String): void -> Creates a text input widget with a given name and default value

comboboxコマンド(dbutils.widgets.combobox)

指定されたプログラム名、デフォルト値、選択肢、およびオプションのラベルを使用してcomboboxウィジェットを作成し、表示します。

このコマンドのヘルプを表示するには、dbutils.widgets.help("combobox")を実行します。

この例では、プログラム名が fruits_combobox のcomboboxウィジェットを作成して表示します。applebananacoconutdragon fruit の選択肢が提供され、初期値は banana に設定されます。このcomboboxウィジェットには Fruits というラベルが付いています。この例は、comboboxウィジェットの初期値 banana を出力して終了します。

dbutils.widgets.combobox(
  name='fruits_combobox',
  defaultValue='banana',
  choices=['apple', 'banana', 'coconut', 'dragon fruit'],
  label='Fruits'
)

print(dbutils.widgets.get("fruits_combobox"))

# banana
dbutils.widgets.combobox(
  name='fruits_combobox',
  defaultValue='banana',
  choices=list('apple', 'banana', 'coconut', 'dragon fruit'),
  label='Fruits'
)

print(dbutils.widgets.get("fruits_combobox"))

# [1] "banana"
dbutils.widgets.combobox(
  "fruits_combobox",
  "banana",
  Array("apple", "banana", "coconut", "dragon fruit"),
  "Fruits"
)

print(dbutils.widgets.get("fruits_combobox"))

// banana

getコマンド(dbutils.widgets.get)

指定されたプログラム名を持つウィジェットの現在値を取得します。このプログラム名は、次のいずれかになります。

  • ノートブック内のカスタム・ウィジェットの名前(例: fruits_combobox または toys_dropdown

  • ノートブック タスクの一部としてノートブックに渡されるカスタム パラメーターの名前 (例: name または age)。 詳細については、ジョブの作成 UI のノートブック タスクのパラメーターのカバレッジ、または Jobs API の Trigger a new job 実行 (POST /jobs/run-now) 操作の notebook_params フィールドを参照してください。

このコマンドのヘルプを表示するには、dbutils.widgets.help("get")を実行します。

この例では、fruits_combobox というプログラム名を持つウィジェットの値を取得します。

dbutils.widgets.get('fruits_combobox')

# banana
dbutils.widgets.get('fruits_combobox')

# [1] "banana"
dbutils.widgets.get("fruits_combobox")

// res6: String = banana

この例では、プログラム名が age であるノートブック・タスク・パラメーターの値を取得します。関連するノートブック・タスクの実行時に、このパラメーターは 35 に設定されました。

dbutils.widgets.get('age')

# 35
dbutils.widgets.get('age')

# [1] "35"
dbutils.widgets.get("age")

// res6: String = 35

getArgumentコマンド(dbutils.widgets.getArgument)

指定されたプログラム名を持つウィジェットの現在値を取得します。ウィジェットが存在しない場合は、オプションのメッセージを返すことができます。

注:

このコマンドは非推奨です。 代わりに dbutils.widgets.get を使用してください。

このコマンドのヘルプを表示するには、dbutils.widgets.help("getArgument")を実行します。

この例では、fruits_combobox というプログラム名を持つウィジェットの値を取得します。このウィジェットが存在しない場合は、Error: Cannot find fruits combobox というメッセージが返されます。

dbutils.widgets.getArgument('fruits_combobox', 'Error: Cannot find fruits combobox')

# Deprecation warning: Use dbutils.widgets.text() or dbutils.widgets.dropdown() to create a widget and dbutils.widgets.get() to get its bound value.
# Out[3]: 'banana'
dbutils.widgets.getArgument('fruits_combobox', 'Error: Cannot find fruits combobox')

# Deprecation warning: Use dbutils.widgets.text() or dbutils.widgets.dropdown() to create a widget and dbutils.widgets.get() to get its bound value.
# [1] "banana"
dbutils.widgets.getArgument("fruits_combobox", "Error: Cannot find fruits combobox")

// command-1234567890123456:1: warning: method getArgument in trait WidgetsUtils is deprecated: Use dbutils.widgets.text() or dbutils.widgets.dropdown() to create a widget and dbutils.widgets.get() to get its bound value.
// dbutils.widgets.getArgument("fruits_combobox", "Error: Cannot find fruits combobox")
//                 ^
// res7: String = banana

multiselectコマンド(dbutils.widgets.multiselect)

指定されたプログラム名、デフォルト値、選択肢、およびオプションのラベルを持つ複数選択ウィジェットを作成して表示します。

このコマンドのヘルプを表示するには、dbutils.widgets.help("multiselect")を実行します。

この例では、days_multiselect というプログラム名のウィジェットを作成して表示します。Monday から Sunday までの選択肢があり、初期値は Tuesday に設定されます。この複数選択ウィジェットには Days of the Week というラベルが付いています。この例は、複数選択ウィジェットの初期値:Tuesday を出力することで終了します。

dbutils.widgets.multiselect(
  name='days_multiselect',
  defaultValue='Tuesday',
  choices=['Monday', 'Tuesday', 'Wednesday', 'Thursday',
    'Friday', 'Saturday', 'Sunday'],
  label='Days of the Week'
)

print(dbutils.widgets.get("days_multiselect"))

# Tuesday
dbutils.widgets.multiselect(
  name='days_multiselect',
  defaultValue='Tuesday',
  choices=list('Monday', 'Tuesday', 'Wednesday', 'Thursday',
    'Friday', 'Saturday', 'Sunday'),
  label='Days of the Week'
)

print(dbutils.widgets.get("days_multiselect"))

# [1] "Tuesday"
dbutils.widgets.multiselect(
  "days_multiselect",
  "Tuesday",
  Array("Monday", "Tuesday", "Wednesday", "Thursday",
    "Friday", "Saturday", "Sunday"),
  "Days of the Week"
)

print(dbutils.widgets.get("days_multiselect"))

// Tuesday

removeコマンド(dbutils.widgets.remove)

指定したプログラム名を持つウィジェットを削除します。

このコマンドのヘルプを表示するには、dbutils.widgets.help("remove")を実行します。

重要:

1つのウィジェットを削除するコマンドを追加した場合、同じセル内に後続のコマンドを追加してウィジェットを作成することはできません。ウィジェットは別のセル内に作成する必要があります。

この例では、プログラム上の名前が fruits_combobox のウィジェットを削除します。

dbutils.widgets.remove('fruits_combobox')
dbutils.widgets.remove('fruits_combobox')
dbutils.widgets.remove("fruits_combobox")

removeAllコマンド(dbutils.widgets.removeAll)

ノートブックからすべてのウィジェットを削除します。

このコマンドのヘルプを表示するには、dbutils.widgets.help("removeAll")を実行します。

重要:

すべてのウィジェットを削除するコマンドを追加した場合、同じセル内に後続のコマンドを追加してウィジェットを作成することはできません。ウィジェットは別のセル内に作成する必要があります。

この例では、ノートブックからすべてのウィジェットを削除します。

dbutils.widgets.removeAll()
dbutils.widgets.removeAll()
dbutils.widgets.removeAll()

textコマンド(dbutils.widgets.text)

指定されたプログラム名、デフォルト値、およびオプションのラベルを持つテキスト・ウィジェットを作成し、表示します。

このコマンドのヘルプを表示するには、dbutils.widgets.help("text")を実行します。

この例では、プログラム名 your_name_textのテキスト・ウィジェットを作成して表示します。初期値は Enter your name に設定されます。このテキスト・ウィジェットには、Your name というラベルが付いています。この例は、テキスト・ウィジェットの初期値:Enter your name を出力することで終了します。

dbutils.widgets.text(
  name='your_name_text',
  defaultValue='Enter your name',
  label='Your name'
)

print(dbutils.widgets.get("your_name_text"))

# Enter your name
dbutils.widgets.text(
  name='your_name_text',
  defaultValue='Enter your name',
  label='Your name'
)

print(dbutils.widgets.get("your_name_text"))

# [1] "Enter your name"
dbutils.widgets.text(
  "your_name_text",
  "Enter your name",
  "Your name"
)

print(dbutils.widgets.get("your_name_text"))

// Enter your name

DatabricksユーティリティAPIライブラリ

重要:

Databricks ユーティリティ API ( dbutils-api ) ライブラリは非推奨です。 このライブラリはまだ利用可能ですが、Databricks ではdbutils-apiライブラリに対する新機能の予定はありません。

Databricks では、代わりに次のライブラリのいずれかを使用することをお勧めします。

アプリケーションを実稼働ジョブとしてデプロイする前に、アプリケーションをコンパイル、構築、テストすると、アプリケーション開発を加速するのに役立ちます。Databricksユーティリティに対してコンパイルできるようにするために、Databricksは dbutils-api ライブラリを提供します。Maven RepositoryウェブサイトのDBUtils APIウェブページから dbutils-api ライブラリをダウンロードするか、ビルドファイルに依存関係を追加してライブラリをインクルードすることができます。

  • SBT

    libraryDependencies += "com.databricks" % "dbutils-api_TARGET" % "VERSION"
    
  • Maven

    <dependency>
        <groupId>com.databricks</groupId>
        <artifactId>dbutils-api_TARGET</artifactId>
        <version>VERSION</version>
    </dependency>
    
  • Gradle

    compile 'com.databricks:dbutils-api_TARGET:VERSION'
    

TARGET を目的のターゲット (例: 2.12) に置き換え、 VERSION を目的のバージョン (例:0.0.5) に置き換えます。利用可能なターゲットとバージョンのリストについては、Maven RepositoryウェブサイトのDBUtils APIウェブページを参照してください。

このライブラリに対してアプリケーションを構築すると、アプリケーションをデプロイできます。

重要:

dbutils-api ライブラリを使用すると、 dbutils を使用するアプリケーションをローカルでコンパイルできますが、実行することはできません。アプリケーションを実行するには、Databricksにデプロイする必要があります。

制限事項

エグゼキューター内で dbutils を呼び出すと、予期しない結果が生じたり、エラーが発生する可能性があります。

dbutils を使用してエグゼキューター上でファイルシステム操作を実行する必要がある場合は、より高速でスケーラブルな代替手段がいくつかあります。

エグゼキューターの詳細については、Apache Sparkウェブサイトの「クラスターモードの概要」を参照してください。