Databricks Utilities (dbutils) 参考

本文是 Databricks Utilities (dbutils) 的参考。 dbutils 实用工具在 Python、R 和 Scala 笔记本中可用。 可以使用该实用工具来:

  • 高效处理文件和对象存储。
  • 使用机密。

如何:列出实用工具列出命令显示命令帮助

实用工具:数据fs作业笔记本机密小组件实用工具 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

数据实用工具 (dbutils.data)

重要

此功能目前以公共预览版提供。

注意

可在 Databricks Runtime 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

summarize 命令 (dbutils.data.summarize)

计算并显示 Apache Spark DataFrame 或 pandas DataFrame 的摘要统计信息。 此命令可用于 Python、Scala 和 R。

此命令会分析数据帧的完整内容。 为非常大的数据帧运行此命令可能非常昂贵。

要显示此命令的相关帮助,请运行 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)

请注意,可视化效果使用 SI 表示法来简洁地呈现小于 0.01 或大于 10000 的数字值。 例如,数字值 1.25e-15 将呈现为 1.25f。 例外:可视化效果对 1.0e9 (giga) 使用“B”而不是“G”。

文件系统实用工具 (dbutils.fs)

警告

所有 dbutils.fs 方法的 Python 实现都使用 snake_case 而不是 camelCase 进行关键字格式设置。

例如:虽然 dbutils.fs.help() 显示了 extraConfigs 的选项 dbutils.fs.mount(),但在 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.chinacloudapi.cn",
  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.chinacloudapi.cn/<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 存储

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 存储

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 存储

rm 命令 (dbutils.fs.mv)

移除文件或目录,并可选择删除其所有内容。 如果指定了文件,则忽略递归参数。 如果指定了目录,则在已禁用递归且目录不为空的情况下,将会发生错误。

要显示此命令的相关帮助,请运行 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 存储

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.chinacloudapi.cn",
  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.chinacloudapi.cn/<directory-name>",
  mountPoint = "/mnt/<mount-name>",
  extraConfigs = Map("<conf-key>" -> dbutils.secrets.get(scope = "<scope-name>", key = "<key-name>")))

作业实用工具 (dbutils.jobs)

子实用工具:taskValues

注意

在 Databricks Runtime 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 Runtime 7.3 及更高版本中可用。

此子实用工具只适用于 Python。

提供用于利用作业任务值的命令。

使用此子实用工具在作业运行过程中设置和获取任意值。 这些值称为“任务值”。 可在同一作业运行中访问下游任务中的任务值。 例如,可以在作业运行中的不同任务之间传递标识符或指标,例如有关机器学习模型评估的信息。 每个任务都可以设置多个任务值或/和获取这些值。 每个任务值在同一个任务中都具有一个唯一的键。 此唯一键称为任务值的键。 使用任务名称和任务值的键访问任务值。

要显示此子实用工具的相关帮助,请运行 dbutils.jobs.taskValues.help()

get 命令 (dbutils.jobs.taskValues.get)

注意

在 Databricks Runtime 7.3 及更高版本中可用。

此命令仅适用于 Python。

在 Databricks Runtime 10.4 及更早版本上,如果 get 找不到任务,则将引发 Py4JJavaError 而不是 ValueError

获取当前作业运行中指定任务的指定任务值的内容。

要显示此命令的相关帮助,请运行 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 时返回的可选值。 default 不能为 None
  • debugValue 是一个可选值,如果尝试从在作业外部运行的笔记本中获取任务值,则会返回该值。 如果要手动运行笔记本并返回一些值(而不是默认引发 TypeError),则它在调试过程中很有用。 debugValue 不能为 None

如果尝试从在作业外部运行的笔记本中获取任务值,则此命令将默认引发 TypeError。 但如果在命令中指定了 debugValue 参数,则会返回 debugValue 的值而不是引发 TypeError

set 命令 (dbutils.jobs.taskValues.set)

注意

在 Databricks Runtime 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 是任务值的键。 此键对于任务必须是独一无二的。 也就是说,如果两个不同的任务分别使用 K 键设置任务值,则这两个不同的任务值具有相同的键 (K)。
  • value 是此任务值键的值。 此命令必须能够在内部以 JSON 格式表示值。 值的 JSON 表示形式的大小不能超过 48 KiB。

如果尝试从在作业外部运行的笔记本中设置任务值,则此命令不执行任何操作。

库实用工具 (dbutils.library)

dbutils.library 子模块中的大多数方法已弃用。 请参阅库实用工具 (dbutils.library)(旧版)

你可以需要在 Azure Databricks 上以编程方式重启 Python 进程,以确保本地安装的或升级的库在当前 SparkSession 的 Python 内核中正常运行。 为此,请运行 dbutils.library.restartPython 命令。 请参阅在 Azure Databricks 上重启 Python 进程

notebook 实用工具 (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

注意

如果运行包含的查询在后台运行结构化流式处理,则调用 dbutils.notebook.exit() 不会终止运行。 只要查询在后台执行,运行就会继续执行。 可单击查询单元格中的“取消”或运行 query.stop() 来停止在后台运行的查询。 查询停止时,可使用 dbutils.notebook.exit() 终止运行。

run 命令 (dbutils.notebook.exit)

运行笔记本并返回其退出值。 默认情况下,笔记本将在当前群集中运行。

注意

run 命令返回的字符串值的最大长度为 5 MB。 请参阅获取单个运行的输出 (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

机密实用工具 (dbutils.secrets)

命令:getgetByteslistlistScopes

利用机密实用工具可以存储和访问敏感的凭据信息,而无需使其在笔记本中可见。 请参阅机密管理在笔记本中使用机密。 要列出可用命令,请运行 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.get)

列出指定范围内的机密的元数据。

要显示此命令的相关帮助,请运行 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 小组件

要列出可用命令,请运行 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 结束。

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)

使用指定的编程名称、默认值、选项和可选标签创建并显示一个 dropdown 小组件。

要显示此命令的相关帮助,请运行 dbutils.widgets.help("dropdown")

此示例创建并显示编程名称为 toys_dropdown 的 dropdown 小组件。 它提供了 alphabet blocksbasketballcapedoll 选项并设置为初始值 basketball。 此 dropdown 小组件包含一个随附的标签 Toys。 此示例以打印 dropdown 小组件的初始值 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 中的笔记本任务的参数覆盖率或作业 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)

创建并显示具有指定编程名称、默认值、选项和可选标签的 multiselect 小组件。

要显示此命令的相关帮助,请运行 dbutils.widgets.help("multiselect")

此示例创建并显示编程名称为 days_multiselect 的 multiselect 小组件。 它通过 Sunday 提供了 Monday 选项并设置为初始值 Tuesday。 此 multiselect 小组件具有随附的标签 Days of the Week。 此示例以打印 multiselect 小组件的初始值 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)

创建并显示具有指定编程名称、默认值和可选标签的 text 小组件。

要显示此命令的相关帮助,请运行 dbutils.widgets.help("text")

此示例创建并显示编程名称为 your_name_text 的 text 小组件。 此值设置为初始值 Enter your name。 此 text 小组件包含一个随附的标签 Your name。 此示例以打印 text 小组件的初始值 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 实用工具 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 的应用程序,但不允许你运行它。 若要运行该应用程序,必须将其部署到 Azure Databricks 中。

限制

在执行程序内调用 dbutils 可能会产生意外的结果或可能导致错误。

如果需要使用 dbutils 在执行程序上运行文件系统操作,可以使用以下几种可快速且更具扩展性的替代方法:

有关执行器的信息,请参阅 Apache Spark 网站上的集群模式概述