使用 DuckDB 快速上手 dbt v1

使用 DuckDB 快速上手 dbt v1

简介

本快速入门指南介绍如何将 dbt v1 与 DuckDB 配合使用,帮助你快速、高效地完成配置。DuckDB 是面向分析工作负载的开源数据库管理系统,旨在提供快速、便捷的大型数据集访问能力,很适合数据分析任务。

本指南覆盖 DuckDB 与 dbt v1 命令行界面(CLI)的用法。关于 dbt v2 专用的 DuckDB 配置,请参阅DuckDB 配置。

本指南将演示如何:

  • 利用 dbt Labs 提供的模板创建虚拟开发环境。
  • 搭建功能完整的 dbt 环境及可以运行的项目。Codespace 会自动连接 DuckDB 数据库,并载入虚构咖啡店 Jaffle Shop 一年的数据。这家店在美国多个城市销售食品和饮料。
  • 完成 jaffle_shop_duckdb 仓库说明的操作。若想深入了解底层代码,请阅读 Jaffle Shop 模板的 README。
  • 在环境的终端中运行任意 dbt 命令。
  • 为 Jaffle Shop 生成更大的数据集,例如将一年的数据扩展为五年。

还可以通过 dbt Learn 课程与工作坊进一步学习。

相关内容

前提条件

  • 将 DuckDB 与 dbt v1 配合使用时,需要使用 CLI。当前 dbt platform 不支持 DuckDB。
  • 需要掌握一些终端基础,尤其是 cd、ls 和 pwd,以便在计算机的目录结构中导航。
  • 拥有 GitHub 账号。

为 dbt v1 配置 DuckDB

本节分别说明如何在本地 Mac、Windows 环境以及浏览器中完成设置。

仓库中的 requirements.txt 用于安装 dbt v1、DuckDB 和其他必要依赖。查看这个文件即可了解将安装哪些内容。它通常位于项目根目录,与 dbt_project.yml 等关键文件放在一起;后面的步骤也会介绍其用法。

下面是项目文件布局示例:

/my_dbt_project/
├── dbt_project.yml
├── models/
│   ├── my_model.sql
├── tests/
│   ├── my_test.sql
└── requirements.txt

更多信息请参阅DuckDB 配置。

本地环境

1. 克隆仓库。在终端中运行下面的命令,克隆 Jaffle Shop Git 仓库:

git clone https://github.com/dbt-labs/jaffle_shop_duckdb.git

2. 进入目录。在命令行中切换到 jaffle_shop_duckdb:

cd jaffle_shop_duckdb

3. 在虚拟环境中安装 dbt v1 和 DuckDB。

Mac 示例

python3 -m venv venv
source venv/bin/activate
python3 -m pip install --upgrade pip
python3 -m pip install -r requirements.txt
source venv/bin/activate

Windows 示例

python -m venv venv
venv\Scripts\activate.bat
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
venv\Scripts\activate.bat

Windows PowerShell 示例

python -m venv venv
venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
venv\Scripts\Activate.ps1

4. 运行 dbt 命令,确认 profile 配置正确。

  • dbt seed:将项目 seed-paths 目录中的 CSV 文件载入数据仓库。
  • dbt compile:根据项目源文件生成可执行 SQL。
  • dbt run:编译并运行项目。
  • dbt test:编译并测试项目。
  • dbt build:编译、运行并测试项目。
  • dbt docs generate:生成项目文档。
  • dbt docs serve:在8080端口启动 Web 服务器,提供本地文档,并在默认浏览器中打开文档站点。

完整说明请参阅 dbt 命令参考。以下为原文给出的成功输出示例:

(venv) ➜  jaffle_shop_duckdb git:(duckdb) dbt build
15:10:12  Running with dbt=x.y.z
15:10:13  Registered adapter: duckdb=x.y.z
15:10:13  Found 5 models, 3 seeds, 20 data tests, 416 macros
15:10:13  
15:10:14  Concurrency: 24 threads (target='dev')
15:10:14  
15:10:14  1 of 28 START seed file main.raw_customers ..................................... [RUN]
15:10:14  2 of 28 START seed file main.raw_orders ........................................ [RUN]
15:10:14  3 of 28 START seed file main.raw_payments ...................................... [RUN]
....

15:10:15  27 of 28 PASS relationships_orders_customer_id__customer_id__ref_customers_ .... [PASS in 0.32s]
15:10:15  
15:10:15  Finished running 3 seeds, 3 view models, 20 data tests, 2 table models in 0 hours 0 minutes and 1.52 seconds (1.52s).
15:10:15  
15:10:15  Completed successfully
15:10:15  
15:10:15  Done. PASS=28 WARN=0 ERROR=0 SKIP=0 TOTAL=28

查询数据时,以下命令很有用:

  • dbt show --select "raw_orders":对数据仓库执行查询,在终端中预览结果。
  • dbt source 提供 dbt source freshness 子命令;后者用于检查指定源表的新鲜度,即数据是否足够新。

故障排查

Could not set lock on file 错误

IO Error: Could not set lock on file "jaffle_shop.duckdb": Resource temporarily unavailable

这是 DuckDB 的一个已知问题。尝试断开所有锁定数据库的会话。如果使用 DBeaver,可能需要关闭 DBeaver,单纯断开连接并不总是有效。

最后的办法是删除数据库文件,让操作恢复,但这会丢失全部数据。

Web 浏览器

  1. 登录 GitHub 后,前往 jaffle-shop-template 仓库。
  2. 点击页面顶部的 Use this template,选择 Create new repository。
  3. 完成新仓库选项设置后,点击 Create repository from template。
  4. 在新仓库页面顶部点击 Code,在 Codespaces 选项卡下选择 Create codespace on main。根据本机设置,这会打开带有 VSCode 开发环境的浏览器标签页,或在新的 VSCode 窗口中打开 Codespace。
  5. 等待 postCreateCommand 完成,Codespace 构建可能需要数分钟。
等待 postCreateCommand 完成
等待 postCreateCommand 完成

命令完成后即可使用 Codespace 开发环境。原先运行命令的终端会关闭,并在新终端中显示提示符。

6. 在终端提示符下可以运行任意 dbt 命令,例如:

/workspaces/test (main) $ dbt build

还可以使用 duckcli 从命令行查询数据仓库,或在 reports 目录提供的 Evidence 项目中构建报表。

完整信息请参阅 dbt 命令参考。常用命令包括 dbt compile(生成可执行 SQL)、dbt run(编译并运行)、dbt test(编译并测试)和 dbt build(编译、运行并测试)。

本地存储

DuckDB 将数据保存到本机的 .duckdb 文件中。文件位置由 profiles.yml 中的 path 字段定义。

本指南的项目使用 jaffle_shop.duckdb 文件。运行 dbt build 后,可以用以下命令确认数据库文件已创建:

ls -lah *.duckdb

项目目录中应出现 jaffle_shop.duckdb,其中包含 dbt 构建的表和视图,并会在多次运行之间保留。

如果删除这个文件:

rm *.duckdb

再次运行 dbt build 会重新创建它。

生成更大的数据集

如果希望处理更多 Jaffle Shop 数据,可以在 Codespace 中生成任意年数的虚构数据。

1. 在终端中安装 Python 包 jafgen:

python -m pip install jafgen

2. 安装完成后运行:

jafgen --years NUMBER_OF_YEARS

将 NUMBER_OF_YEARS 替换为要模拟的年数。例如,六年的数据使用 jafgen --years 6。命令生成 CSV 文件并保存到 jaffle-data 目录,随后根据 sources.yml 与 dbt-duckdb 适配器自动作为数据源读取。

年数越多,Jaffle Shop 门店的规模和数量也会增长,因此生成数据所需时间会呈指数增加。为平衡数据规模与构建时间,dbt Labs 建议最多生成六年。

后续步骤

现在 dbt v1、DuckDB 和 Jaffle Shop 数据已经准备好,可以继续探索 dbt 的能力。以下资料有助于理解项目和命令:

在掌握 DuckDB 基础后,还可以通过编写项目文档、提交更改和安排作业,进一步完善配置。

编写项目文档

  • 使用 dbt docs generate,将项目与数据仓库的信息编译到 manifest.json 和 catalog.json。
  • 运行 dbt docs serve,使用生成的 JSON 文件创建本地网站,从浏览器查看项目文档。
  • 在 YAML 文件中使用 description 键,为模型、列和源添加描述。

提交更改

提交更改,确保仓库包含最新代码。在为项目创建的 GitHub 仓库工作目录中运行:

git add .
git commit -m "Your commit message"
git push

然后返回 GitHub 仓库页面,确认新文件已经加入。

安排作业

  1. 确认 dbt v1 已安装,并配置为连接 DuckDB 实例。
  2. 创建 dbt 项目,定义模型、种子数据和测试。
  3. 使用 Prefect 等调度器安排 dbt 运行。可以创建有向无环图(DAG),按指定间隔触发 dbt 命令。
  4. 编写脚本,执行 dbt run、dbt test 等命令。
  5. 使用选定的调度器,按所需频率运行脚本。

恭喜完成本指南!

来源与许可

来源:dbt Developer Hub:Quickstart for dbt v1 using DuckDB,© 2026 dbt Labs, LLC。中文翻译调整了排版,保留原示例、输出与链接。示例输出来自原文,不代表本地实际运行。文档仓库按 Apache License 2.0 提供,完整许可如下:

Apache License 2.0
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright \{yyyy\} \{name of copyright owner\}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容