LoginSignup
1
5

More than 1 year has passed since last update.

Databricks Utilities | Databricks on AWS [2022/6/21時点]の翻訳です。

Databricksクイックスタートガイドのコンテンツです。

本書は抄訳であり内容の正確性を保証するものではありません。正確な内容に関しては原文を参照ください。

Databricksユーティリティ(dbutils)は、タスクのパワフルな組み合わせの実行を容易にします。ノートブックのパラメーター化、チェイン、シークレットを取り扱うなどのケースで、オブジェクトストレージと効率的に連携するためにユーティリティを活用することができます。dbutilsはノートブック外ではサポートされていません。

重要!
エグゼキューターからのdbutilsの呼び出しは予期しない結果になることがあります。dbutilsの制限とワークアラウンドとなりうる代替策については制限を参照ください。

dbutilsユーティリティは、Python、R、Scalaノートブックで使用することができます。

How to: ユーティリティの一覧コマンドの一覧コマンドヘルプの表示

ユーティリティ: クレディンシャルデータファイルシステムライブラリノートブックシークレットウィジェットUtilities 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
fs: DbfsUtils -> Manipulates the Databricks filesystem (DBFS) from the console
library: LibraryUtils -> Utilities for session isolated libraries
notebook: NotebookUtils -> Utilities for the control flow of a notebook (EXPERIMENTAL)
secrets: SecretUtils -> Provides utilities for leveraging secrets within notebooks
widgets: WidgetsUtils -> Methods to create and get bound value of input widgets inside notebooks

ユーティリティで使用できるコマンドの一覧

ユーティリティのそれぞれのコマンドの簡単な説明文とともにコマンドの一覧を表示するには、ユーティリティのプログラム名の後に.help()をつけて実行します。

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

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

クレディンシャルユーティリティ(dbutils.credentials)

コマンド: assumeRoleshowCurrentRoleshowRoles

クレディンシャルユーティリティを用いることで、ノートブック内でクレディンシャルを取り扱うことができます。このユーティリティはクレディンシャルパススルーが有効化されたクラスターでのみ利用できます。利用可能なコマンドの一覧を表示するには、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

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

Amazon S3の認証を受けるためのクレディンシャルを検索する際に、委任を受けるAWSのアイデンティティとアクセス管理(IAM)ロールのAmazonリソース名(ARN)を設定します。このコマンドを実行した後は、オブジェクトにアクセスするためにsc.textFile("s3a://my-bucket/my-file.csv")のようなS3アクセスコマンドを実行できるようになります。

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

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

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

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

// res0: Boolean = true

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

現在設定されているAWSアイデンティティとアクセス管理(IAM)ロールを一覧します。

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

Python
dbutils.credentials.showCurrentRole()

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

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

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

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

利用できるAWSアイデンティティとアクセス管理(IAM)ロールを一覧します。

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

Python
dbutils.credentials.showRoles()

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

# [[1]]
# [1] "arn:aws:iam::123456789012:role/my-role-a"
#
# [[2]]
# [1] "arn:aws:iam::123456789012:role/my-role-b"
Scala
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ランタイム9.0以降で利用できます。

コマンド: summarize

データユーティリティを使うことで、データセットの理解、解釈の役に立ちます。利用可能なコマンド一覧を表示するには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データフレームかpandasデータフレームのサマリーの統計情報を計算、表示します。このコマンドはPython、Scala、Rで使用することができます。

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

Databricksランタイム10.1以降では、計算される統計情報の精度を調整するために、追加のpreciseパラメーターを使用することができます。

プレビュー
本機能はパブリックプレビューです。

  • preciseがfalseに設定(デフォルト)されている場合、実行時間を削減するために近似値を含むいくつかの統計値を返却します。

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

コマンド: cpheadlsmkdirsmountmountsmvputrefreshMountsrmunmountupdateMount

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ランタイム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
aws_bucket_name = "my-bucket"
mount_name = "s3-my-bucket"

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

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

他のコードサンプルについては、DatabricksにおけるAmazon S3の取り扱いをご覧ください。

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

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

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

Python
dbutils.fs.mounts()

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

他のコードサンプルについては、DatabricksにおけるAmazon S3の取り扱いをご覧ください。

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

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

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

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

ファイルやディレクトリを削除します。

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

このサンプルでは/tmphello_db.txtというファイルを削除します。

Python
dbutils.fs.rm("/tmp/hello_db.txt")

# Out[8]: True
R
dbutils.fs.rm("/tmp/hello_db.txt")

# [1] TRUE
Scala
dbutils.fs.rm("/tmp/hello_db.txt")

// res6: Boolean = true

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

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

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

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

他のコードサンプルについては、DatabricksにおけるAmazon S3の取り扱いをご覧ください。

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

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

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

このコマンドはDatabricksランタイム10.2以降で使用できます。

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

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

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

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

サブユーティリティ: taskValues

注意
Databricksランタイム7.3以降で利用できます。

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

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

Provides utilities for leveraging jobs features.

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

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

コマンド: getset

注意
Databricksランタイム7.3以降で利用できます。

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

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

ジョブの実行中に任意の値を設定、取得するためにこのサブユーティリティを使用します。これらの値はタスクバリューと呼びます。同じジョブ実行の中の後段のタスクでタスクバリューにアクセスすることができます。例えば、IDや機械学習モデルの評価に関する情報などのメトリクスをジョブ実行の中の別のタスクでやり取りすることができます。それぞれのタスクバリューは同じタスク内でユニークなキーを持ちます。ユニークキーはタスクバリューのキーとなります。タスクバリューはタスク名とタスクバリューのキーと関連づけられます。

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

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

注意
Databricksランタイム7.3以降で利用できます。

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

Databricksランタイム10.4以前では、getがタスクを見つけられなかった場合、ValueErrorではなくPy4JJavaErrorが発生します。

現在のジョブ実行で特定のタスクの特定のタスクバリューの中身を取得します。

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

サンプルは以下のようになります。

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

上の例では、

  • taskKeyはジョブ内のタスク名となります。このタスクを発見できない場合、ValueErrorが発生します。
  • keysetコマンド(dbutils.jobs.taskValues.set)で設定したタスクバリューのキーとなります。コマンドがこのタスクバリューキーを発見できない場合(defaultが指定されない場合)、ValueErrorが発生します。
  • defaultはタスクバリューのkeyが見つからない場合、このタスクバリューが返却されるオプションの値です。defaultNoneを指定することはできません。
  • debugValueはジョブの外で実行しているノートブック内からタスクバリューを取得しようとした際に返却されるオプションの値です。これは、ノートブックを手動で実行し、デフォルトのTypeErrorを引き起こすのではなく何かしらの値を返却することで、デバッグの際に有用です。debugValueNoneを指定することはできません。

ジョブの外で実行されているノートブックからタスクバリューを取得しようとすると、このコマンドはデフォルトではTypeErrorとなります。しかし、コマンドでdebugValueを指定すると、TypeErrorではなくdebugValueが返却されます。

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

注意
Databricksランタイム7.3以降で利用できます。

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

タスクバリューを設定あるいは更新します。ジョブの実行(ラン)ごとに最大250のタスクバリューを設定することができます。

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

以下に例を示します。

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

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

上の例では、

  • keyはタスクバリューのキーの名前です。名前はジョブでユニークである必要があります。
  • valueはタスクバリューキーに対応する値です。このコマンドでは内部的にJSONで表現可能な値である必要があります。値のJSON表現のサイズは48 KiBを超えることができません。

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

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

注意
ライブラリユーティリティは非推奨となりました。

原文を参照ください。

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

コマンド: exitrun

ノートブックユーティリティを用いることで、複数のノートブックをチェーンさせることができ、結果に基づいて動作させることができます。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.

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

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

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

注意
runコマンドから返却される文字列の最大長は5MBです。Get the output for a single run(GET /jobs/runs/get-output)をご覧ください。

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

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

Python
dbutils.notebook.exit("Exiting from My Other Notebook")
Scala
dbutils.notebook.run("My Other Notebook", 60)

// res2: String = Exiting from My Other Notebook

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

コマンド: getgetByteslistlistScopes

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

シークレットユーティリティを用いることで、ノートブックに表示することなしにセンシティブなクレディンシャル情報を格納、アクセスすることができます。Databricksにおけるシークレットの管理ノートブックからシークレットを使用するをご覧ください。

利用可能なコマンドを表示するには、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はノートブックに表示されるかもしれないシークレットの値を検閲する努力を払いますが、そのようなユーザーがシークレットを読み込むことを防ぐことは不可能です。詳細は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
my_secret = dbutils.secrets.getBytes(scope="my-scope", key="my-key")
my_secret.decode("utf-8")

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

# [1] "a1!b2@c3#"
Scala
val mySecret = dbutils.secrets.getBytes(scope="my-scope", key="my-key")
val convertedString = new String(mySecret)
println(convertedString)

// a1!b2@c3#
// mySecret: Array[Byte] = Array(97, 49, 33, 98, 50, 64, 99, 51, 35)
// convertedString: String = a1!b2@c3#

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

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

コマンド: comboboxdropdowngetgetArgumentmultiselectremoveremoveAlltext

ウィジェットユーティリティを用いることでノートブックをパラメーター化することができます。Databricksのwidget(ウィジェット)をご覧ください。

利用可能なコマンドを表示するには、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 Utilities APIライブラリ

アプリケーション開発を加速するために、プロダクションのジョブとしてデプロイする前に、アプリケーションのコンパイル、ビルド、テストを行うことは有用です。Databricksユーティリティのコンパイルを可能にするために、Databricksはdbutils-apiライブラリを提供しています。Maven Repository websiteのDBUtils APIWebページからdbutils-apiライブラリをダウンロードするか、あるいはビルドファイルに依存関係を追加することでライブラリを追加することができます。

  • SBT

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

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

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

TARGETは希望のターゲット(例えば2.12)、VERSIONを希望のバージョン(例えば0.0.5)に置き換えてください。利用できるターゲットとバージョンについては、Maven Repository websiteのDBUtils APIをご覧ください。

このライブラリに対してアプリケーションをビルドすることで、アプリケーションをデプロイすることが可能になります。

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

制限

エグゼキューター内でのdbutilsの呼び出しは予期せない結果を引き起こし、エラーとなる場合があります。

dbutilsを用いたエグゼキューター上でのファイルシステムオペレーションが必要な場合には、より高速かつスケーラブルな代替案が存在します。

  • ファイルのコピーや移動のオペレーションに対しては、Parallelize filesystem operationsで説明されているファイルシステムオペレーションのより高速なオプションをチェックしてみてください。
  • 一覧と削除のオペレーションについては、How to list and delete files faster in Databricksで、Sparkを用いた並列の一覧表示、削除の方法を参照することができます。

エグゼキューターに関しては、Apache Spark websiteのCluster Mode Overviewをご覧ください。

Databricks 無料トライアル

Databricks 無料トライアル

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5