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ユーティリティで利用できるコマンドの一覧を表示します。
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
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()
をつけて実行します。
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>")
をつけて実行します。
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
assumeRoleコマンド(dbutils.credentials.assumeRole)
Amazon S3の認証を受けるためのクレディンシャルを検索する際に、委任を受けるAWSのアイデンティティとアクセス管理(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アイデンティティとアクセス管理(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アイデンティティとアクセス管理(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ランタイム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)
コマンド: cp、head、ls、mkdirs、mount、mounts、mv、put、refreshMounts、rm、unmount、updateMount
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ランタイム10.2以降で利用できます。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")
他のコードサンプルについては、DatabricksにおけるAmazon S3の取り扱いをご覧ください。
mountsコマンド(dbutils.fs.mounts)
DBFS内に現在何がマウントされているかに関する情報を表示します。
このコマンドのヘルプを表示するには、dbutils.fs.help("mounts")
を実行します。
dbutils.fs.mounts()
# Out[11]: [MountInfo(mountPoint='/mnt/databricks-results', source='databricks-results', encryptionType='sse-s3')]
dbutils.fs.mounts()
他のコードサンプルについては、Databricksにおける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")
を実行します。
このサンプルでは、/tmp
にあるhello_db.txt
というファイルに文字列Hello, Databricks!
を書き込みます。ファイルが存在する場合には上書きされます。
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()
rmコマンド(dbutils.fs.rm)
ファイルやディレクトリを削除します。
このコマンドのヘルプを表示するには、dbutils.fs.help("rm")
を実行します。
このサンプルでは/tmp
のhello_db.txt
というファイルを削除します。
dbutils.fs.rm("/tmp/hello_db.txt")
# Out[8]: True
dbutils.fs.rm("/tmp/hello_db.txt")
# [1] TRUE
dbutils.fs.rm("/tmp/hello_db.txt")
// res6: Boolean = true
unmountコマンド(dbutils.fs.unmount)
DBFSマウントポイントを削除します。
このコマンドのヘルプを表示するには、dbutils.fs.help("unmount")
を実行します。
dbutils.fs.unmount("/mnt/<mount-name>")
他のコードサンプルについては、DatabricksにおけるAmazon S3の取り扱いをご覧ください。
updateMountコマンド(dbutils.fs.updateMount)
dbutils.fs.mount
コマンドと似ていますが、新規のマウントポイントを作成するのではなく既存のマウントポイントを更新します。マウントポイントが存在しない場合にはエラーとなります。
このコマンドのヘルプを表示するには、dbutils.fs.help("updateMount")
を実行します。
このコマンドはDatabricksランタイム10.2以降で使用できます。
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)
サブユーティリティ: 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)
注意
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")
を実行します。
サンプルは以下のようになります。
dbutils.jobs.taskValues.get(taskKey = "my-task", \
key = "my-key", \
default = 7, \
debugValue = 42)
上の例では、
-
taskKey
はジョブ内のタスク名となります。このタスクを発見できない場合、ValueError
が発生します。 -
key
はsetコマンド(dbutils.jobs.taskValues.set)で設定したタスクバリューのキーとなります。コマンドがこのタスクバリューキーを発見できない場合(default
が指定されない場合)、ValueError
が発生します。 -
default
はタスクバリューのkey
が見つからない場合、このタスクバリューが返却されるオプションの値です。default
にNone
を指定することはできません。 -
debugValue
はジョブの外で実行しているノートブック内からタスクバリューを取得しようとした際に返却されるオプションの値です。これは、ノートブックを手動で実行し、デフォルトのTypeError
を引き起こすのではなく何かしらの値を返却することで、デバッグの際に有用です。debugValue
にNone
を指定することはできません。
ジョブの外で実行されているノートブックからタスクバリューを取得しようとすると、このコマンドはデフォルトではTypeError
となります。しかし、コマンドでdebugValue
を指定すると、TypeError
ではなくdebugValue
が返却されます。
setコマンド(dbutils.jobs.taskValues.set)
注意
Databricksランタイム7.3以降で利用できます。
このユーティリティは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
はタスクバリューのキーの名前です。名前はジョブでユニークである必要があります。 -
value
はタスクバリューキーに対応する値です。このコマンドでは内部的にJSONで表現可能な値である必要があります。値のJSON表現のサイズは48 KiBを超えることができません。
ジョブの外で実行されているノートブックからタスクバリューを設定しようとしても、このコマンドは何もしません。
ライブラリユーティリティ(dbutils.library)
注意
ライブラリユーティリティは非推奨となりました。
原文を参照ください。
ノートブックユーティリティ(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.
exitコマンド(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
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秒以内に処理を終了しなかった場合には例外がスローされます。
dbutils.notebook.exit("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
このコマンドのヘルプを表示するには、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
のシークレットの値の文字列表現を取得しています。
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#
)を取得しています。
my_secret = dbutils.secrets.getBytes(scope="my-scope", key="my-key")
my_secret.decode("utf-8")
# Out[1]: 'a1!b2@c3#'
my_secret = dbutils.secrets.getBytes(scope="my-scope", key="my-key")
print(rawToChar(my_secret))
# [1] "a1!b2@c3#"
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
というスコープ内のシークレットのメタデータを一覧しています。
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)
コマンド: combobox、dropdown、get、getArgument、multiselect、remove、removeAll、text
ウィジェットユーティリティを用いることでノートブックをパラメーター化することができます。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
という名前のコンボボックスウィジェットを作成し表示します。選択肢としてapple
、banana
、coconut
、dragon fruit
を提供し、初期値をbanana
に設定します。このコンボボックスにはラベルFruits
が表示されます。このサンプルでは、コンボボックスウィジェットの初期値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
dropdownコマンド(dbutils.widgets.dropdown)
指定されたプログラム上の名前、デフォルト値、選択肢、オプションとしてラベルを指定することでドロップダウンのウィジェットを作成し表示します。
このコマンドのヘルプを表示するには、dbutils.widgets.help("dropdown")
を実行します。
このサンプルでは、プログラム上の名称toys_dropdown
という名前のドロップダウンウィジェットを作成し表示します。選択肢としてalphabet blocks
、basketball
、cape
、doll
を提供し、初期値をbasketball
に設定します。このドロップダウンにはラベルToys
が表示されます。このサンプルでは、コンボボックスウィジェットの初期値basketball
を表示して終了しています。
dbutils.widgets.dropdown(
name='toys_dropdown',
defaultValue='basketball',
choices=['alphabet blocks', 'basketball', 'cape', 'doll'],
label='Toys'
)
print(dbutils.widgets.get("toys_dropdown"))
# basketball
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"
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_combobox
やtoys_dropdown
。 - ノートブックタスクの一部としてノートブックに渡されたカスタムパラメーターの名前。例えば、
name
やage
。詳細については、ジョブの作成UIにおけるノートブックタスクのパラメーターのカバー範囲や、Jobs APIの新規ジョブ実行(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")
を実行します。
重要!
ウィジェットを削除するコマンドを追加した場合、同じセルにウィジェットを作成する後続のコマンドを追加することはできません。別のセルでウィジェットを作成する必要があります。
このサンプルでは、プログラム上の名称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 Utilities APIライブラリ
アプリケーション開発を加速するために、プロダクションのジョブとしてデプロイする前に、アプリケーションのコンパイル、ビルド、テストを行うことは有用です。Databricksユーティリティのコンパイルを可能にするために、Databricksはdbutils-api
ライブラリを提供しています。Maven Repository websiteのDBUtils APIWebページからdbutils-api
ライブラリをダウンロードするか、あるいはビルドファイルに依存関係を追加することでライブラリを追加することができます。
-
SBT
ScalalibraryDependencies += "com.databricks" % "dbutils-api_TARGET" % "VERSION"
-
Maven
XML<dependency> <groupId>com.databricks</groupId> <artifactId>dbutils-api_TARGET</artifactId> <version>VERSION</version> </dependency>
-
Gradle
Bashcompile '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をご覧ください。