Databricks Utilities (dbutils) リファレンス

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

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

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

ユーティリティ: datafsjobslibrarynotebooksecretswidgetsユーティリティの API ライブラリ

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

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

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

Python

dbutils.help()

Scala

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 ファイル システム (DBFS) ユーティリティで使用できるコマンドを一覧表示します。

Python

dbutils.fs.help()

R

dbutils.fs.help()

Scala

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 コピー コマンドのヘルプを表示します。

Python

dbutils.fs.help("cp")

R

dbutils.fs.help("cp")

Scala

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

data ユーティリティ (dbutils.data)

重要

この機能はパブリック プレビュー段階にあります。

Note

Databricks Runtime 9.0 以降で使用できます。

コマンド: summarize

data ユーティリティを使用すると、データセットを理解および解釈できます。 使用可能なコマンドを一覧表示するには、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

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

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

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

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

Databricks Runtime 10.1 以降では、計算された統計の有効桁数を調整するために、追加の precise パラメーターを使用できます。

注意

この機能はパブリック プレビュー段階にあります。

  • precise が false (既定値) に設定されている場合、返される一部の統計では、実行時間を短縮するために、概算値が含まれます。
    • カテゴリ列の個別値の数で、高カーディナリティ列に対して最大 5% の相対誤差が発生する可能性があります。
    • 個別値の数が 10000 を超える場合、頻出値の数で、最大 0.01% の誤差が発生する可能性があります。
    • ヒストグラムとパーセンタイルの推定値で、行の総数と相対的に最大 0.01% の誤差が発生する可能性があります。
  • precise が true に設定されている場合、統計は高い精度で計算されます。 数値列のヒストグラムとパーセンタイルを除くすべての統計が正確になります。
    • ヒストグラムとパーセンタイルの推定値で、行の総数と相対的に最大 0.0001% の誤差が発生する可能性があります。

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

この例では、既定で概算値が有効になり、Apache Spark DataFrame の概要統計情報が表示されます。 結果を表示するには、ノートブックでこのコマンドを実行します。 この例は、サンプル データセットに基づいています。

Python

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

R

df <- read.df("/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv", source = "csv", header="true", inferSchema = "true")
dbutils.data.summarize(df)

Scala

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.0e9 (ギガ) に対して、"G" ではなく "B" が使用されます。

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

警告

すべての dbutils.fs メソッドの Python 実装では、キーワードの書式設定では camelCase ではなく snake_case を使用します。

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

コマンド: cpheadlsmkdirsmountmountsmvputrefreshMountsrmunmountupdateMount

ファイル システム ユーティリティを使用すると、「Databricks ファイル システム (DBFS) とは」にアクセスでき、Azure 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 に変更します。

Python

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

# Out[4]: True

R

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

# [1] TRUE

Scala

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 バイトを表示します。

Python

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

# [Truncated to first 25 bytes]
# Out[12]: 'Apache Spark is awesome!\n'

R

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

# [1] "Apache Spark is awesome!\n"

Scala

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.2 以降で使用できます。 R では、modificationTime は文字列として返されます。

Python

dbutils.fs.ls("/tmp")

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

R

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"

Scala

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 を作成します。

Python

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

# Out[15]: True

R

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

# [1] TRUE

Scala

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

// res7: Boolean = true

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

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

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

Python

dbutils.fs.mount(
  source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net",
  mount_point = "/mnt/<mount-name>",
  extra_configs = {"<conf-key>":dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")})

Scala

dbutils.fs.mount(
  source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net/<directory-name>",
  mountPoint = "/mnt/<mount-name>",
  extraConfigs = Map("<conf-key>" -> dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")))

その他のコード例については、「Azure Data Lake Storage Gen2 と Blob Storage にアクセスする」を参照してください。

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

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

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

警告

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

Python

dbutils.fs.mounts()

Scala

dbutils.fs.mounts()

その他のコード例については、「Azure Data Lake Storage Gen2 と Blob Storage にアクセスする」を参照してください。

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

ファイルまたはディレクトリを移動します (ファイル システム間での移動にも対応)。 移動では、コピーの後に削除が実行されます (ファイル システム内の移動でも同様)。

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

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

Python

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

# Out[2]: True

R

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

# [1] TRUE

Scala

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 という名前のファイルに書き込みます。 このファイルが存在する場合、上書きされます。

Python

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

# Wrote 18 bytes.
# Out[6]: True

R

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

# [1] TRUE

Scala

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

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

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

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

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

Python

dbutils.fs.refreshMounts()

Scala

dbutils.fs.refreshMounts()

その他のコード例については、「Azure Data Lake Storage Gen2 と Blob Storage にアクセスする」を参照してください。

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

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

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

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

Python

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

# Out[8]: True

R

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

# [1] TRUE

Scala

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

その他のコード例については、「Azure Data Lake Storage Gen2 と Blob Storage にアクセスする」を参照してください。

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

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

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

警告

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

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

Python

dbutils.fs.updateMount(
  source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net",
  mount_point = "/mnt/<mount-name>",
  extra_configs = {"<conf-key>":dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")})

Scala

dbutils.fs.updateMount(
  source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net/<directory-name>",
  mountPoint = "/mnt/<mount-name>",
  extraConfigs = Map("<conf-key>" -> dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")))

Jobs ユーティリティ (dbutils.jobs)

サブユーティリティ: taskValues

注意

Databricks Runtime 7.3 以降で使用できます。

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

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

Provides utilities for leveraging jobs features.

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

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

コマンド: getset

注意

Databricks Runtime 7.3 以降で使用できます。

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

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

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

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

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

注意

Databricks Runtime 7.3 以降で使用できます。

このコマンドは、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.jobs.taskValues.set) で設定したタスク値のキーの名前です。 コマンドでこのタスク値のキーが見つからない場合は、ValueError が発生します (default が指定されている場合を除く)。
  • default は、key が見つからない場合に返される省略可能な値です。 defaultNone は指定できません。
  • debugValue は、ジョブの外部で実行されているノートブック内からタスク値を取得しようとすると返される省略可能な値です。 これは、ノートブックを手動で実行し、デバッグ中に既定で TypeError を発生させるのではなく値を返す場合に役立ちます。 debugValueNone は指定できません。

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

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

注意

Databricks Runtime 7.3 以降で使用できます。

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

タスク値を設定または更新します。 1 つのジョブ実行に対して、最大 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 以下にする必要があります。

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

Library ユーティリティ (dbutils.library)

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

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

notebook ユーティリティ (dbutils.notebook)

コマンド: exitrun

notebook ユーティリティを使用すると、ノートブックをチェーンし、その結果に基いて処理を行うことができます。 「ノートブックでコードをモジュール化またはリンクする」を参照してください。

使用可能なコマンドを一覧表示するには、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.

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

値を指定してノートブックを終了します。

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

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

Python

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

# Notebook exited: Exiting from My Other Notebook

R

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

# Notebook exited: Exiting from My Other Notebook

Scala

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 です。 1 回の実行の出力の取得 (GET /jobs/runs/get-output) に関する記事を参照してください。

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

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

Python

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

# Out[14]: 'Exiting from My Other Notebook'

Scala

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

// res2: String = Exiting from My Other Notebook

secrets ユーティリティ (dbutils.secrets)

コマンド: getgetByteslistlistScopes

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)

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

警告

管理者、シークレット作成者、およびアクセス許可を付与されたユーザーは、Azure Databricks シークレットを読み取ることができます。 Azure Databricks は、ノートブックに表示される可能性があるシークレットの値を編集しようとしますが、そのようなユーザーがシークレットを読み取れないようにすることはできません。 詳細については、「シークレットの編集」を参照してください。

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

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

Python

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

# Out[14]: '[REDACTED]'

R

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

# [1] "[REDACTED]"

Scala

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#) を取得しています。

Python

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

# Out[1]: b'a1!b2@c3#'

R

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

# [1] 61 31 21 62 32 40 63 33 23

Scala

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 という名前のスコープ内のシークレットのメタデータを一覧表示します。

Python

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

# Out[10]: [SecretMetadata(key='my-key')]

R

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

# [[1]]
# [[1]]$key
# [1] "my-key"

Scala

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

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

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

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

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

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

Python

dbutils.secrets.listScopes()

# Out[14]: [SecretScope(name='my-scope')]

R

dbutils.secrets.listScopes()

# [[1]]
# [[1]]$name
# [1] "my-scope"

Scala

dbutils.secrets.listScopes()

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

widgets ユーティリティ (dbutils.widgets)

コマンド: comboboxdropdowngetgetArgumentmultiselectremoveremoveAlltext

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)

プログラム名、既定値、選択肢、ラベル (省略可能) を指定して、コンボボックス ウィジェットを作成して表示します。

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

この例では、プログラム名が fruits_combobox のコンボボックス ウィジェットを作成して表示します。 選択肢として applebananacoconutdragon fruit を用意しており、初期値は banana に設定しています。 このコンボボックス ウィジェットには、Fruits というラベルが付加されます。 この例は、コンボボックス ウィジェットの初期値である banana を出力して終了します。

Python

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

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

# banana

R

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"

Scala

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

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

// banana

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

プログラム名、既定値、選択肢、ラベル (省略可能) を指定して、ドロップダウン ウィジェットを作成して表示します。

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

この例では、プログラム名が toys_dropdown のドロップダウン ウィジェットを作成して表示します。 選択肢として alphabet blocksbasketballcapedoll を用意しており、初期値は basketball に設定しています。 このドロップダウン ウィジェットには、Toys というラベルが付加されます。 この例は、ドロップダウン ウィジェットの初期値である basketball を出力して終了します。

Python

dbutils.widgets.dropdown(
  name='toys_dropdown',
  defaultValue='basketball',
  choices=['alphabet blocks', 'basketball', 'cape', 'doll'],
  label='Toys'
)

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

# basketball

R

dbutils.widgets.dropdown(
  name='toys_dropdown',
  defaultValue='basketball',
  choices=list('alphabet blocks', 'basketball', 'cape', 'doll'),
  label='Toys'
)

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

# [1] "basketball"

Scala

dbutils.widgets.dropdown(
  "toys_dropdown",
  "basketball",
  Array("alphabet blocks", "basketball", "cape", "doll"),
  "Toys"
)

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

// basketball

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

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

  • ノートブック内のカスタム ウィジェットの名前 (例: fruits_comboboxtoys_dropdown など)。
  • ノートブック タスクの一部としてノートブックに渡されるカスタム パラメーターの名前 (例: nameage など)。 詳しくは、ジョブの作成 UI のノートブック タスクのパラメーターの対象範囲を参照するか、Jobs API の新しいジョブ実行のトリガー (POST /jobs/run-now) 操作の notebook_params フィールドを参照してください。

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

この例では、プログラム名が fruits_combobox であるウィジェットの値を取得します。

Python

dbutils.widgets.get('fruits_combobox')

# banana

R

dbutils.widgets.get('fruits_combobox')

# [1] "banana"

Scala

dbutils.widgets.get("fruits_combobox")

// res6: String = banana

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

Python

dbutils.widgets.get('age')

# 35

R

dbutils.widgets.get('age')

# [1] "35"

Scala

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 が返されます。

Python

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'

R

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"

Scala

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 を出力して終了します。

Python

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

R

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"

Scala

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") を実行します。

重要

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

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

Python

dbutils.widgets.remove('fruits_combobox')

R

dbutils.widgets.remove('fruits_combobox')

Scala

dbutils.widgets.remove("fruits_combobox")

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

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

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

重要

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

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

Python

dbutils.widgets.removeAll()

R

dbutils.widgets.removeAll()

Scala

dbutils.widgets.removeAll()

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

プログラム名、既定値、ラベル (省略可能) を指定して、テキスト ウィジェットを作成して表示します。

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

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

Python

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

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

# Enter your name

R

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"

Scala

dbutils.widgets.text(
  "your_name_text",
  "Enter your name",
  "Your name"
)

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

// Enter your name

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

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

  • 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 リポジトリの Web サイトにある DBUtils API の Web ページを参照してください。

このライブラリに対してアプリケーションをビルドした後、そのアプリケーションをデプロイできます。

重要

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

制限事項

実行プログラムの内部で dbutils を呼び出すと、予期しない結果やエラーが発生する可能性があります。

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

実行プログラムについて詳しくは、Apache Spark の Web サイトでクラスター モードの概要に関する記事を参照してください。