DBT中文社区

    • Register
    • Login
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • 达之云

    开源软件DBT中文社区

    微信号:DBT_CN

    QQ群:551308350

    模型Models使用说明

    使用指南
    1
    1
    1224
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • D
      dazdata last edited by

      dbt core 1.3版本开始支持了SQL模型和Python模型。

      SQL模型
      SQL 模型是一个语句,保存再models文件夹中:

      • 每个文件包含一个select的sql语句
      • 模型名就是自文件名。
      • 模型可以嵌套在models的子目录中

      当你执行 dbt run 命令时,dbt将在模型数据仓库通过将其包装在类似语句:create view as或create table as执行

      例如以下模型:customers
      models/customers.sql

      with customer_orders as (
      select
      customer_id,
      min(order_date) as first_order_date,
      max(order_date) as most_recent_order_date,
      count(order_id) as number_of_orders

      from jaffle_shop.orders
      
      group by 1
      

      )

      select
      customers.customer_id,
      customers.first_name,
      customers.last_name,
      customer_orders.first_order_date,
      customer_orders.most_recent_order_date,
      coalesce(customer_orders.number_of_orders, 0) as number_of_orders

      from jaffle_shop.customers

      left join customer_orders using (customer_id)

      当你执行dbt run customers时,dbt 会将其构建为目标模式中命名的视图:dbt_alice.customers,其中dbt_alice是你在项目配置文件种定义的数据仓库目标角色。

      Python模型
      DBT Python模型可以帮助您解决 SQL 无法解决的问题,您可以在项目直接使用 Python 生态系统中提供的工具包,包括用于数据科学和统计的最新软件包。以前,需要单独的基础结构和业务流程才能在生产环境中运行 Python 转换。dbt 中定义的 Python 转换是内置于项目中的模型,测试、文档和沿袭方面都可用。
      models/my_python_model.py

      import ...

      def model(dbt, session):

      my_sql_model_df = dbt.ref("my_sql_model")
      
      final_df = ...  # stuff you can't write in SQL!
      
      return final_df
      

      models/config.yml
      version: 2

      models:

      • name: my_python_model

        description: My transformation written in Python

        config:
        materialized: table
        tags: ['python']

        columns:

        • name: id
          tests:
          • unique
          • not_null
            tests:
            results
        • custom_generic_test
          替代文字
          SQL+Python,终于在一起了

      在模型之间构建依赖关系
      可以通过使用 ref 函数代替查询中的表名来构建模型之间的依赖关系。使用另一个模型的名称作为 的参数。
      DBT 使用ref函数执行以下操作:

      • 通过创建依赖无环图 (DAG) 来确定运行模型的顺序。
      • 管理单独的环境 — dbt 会将函数中指定的模型替换为ref数据表(或视图)。重要的是,这是环境感知的 — 如果您使用名为 的目标架构运行 dbt,它将从同一架构中的上游表中进行选择。
        替代文字
      1 Reply Last reply Reply Quote 0
      • First post
        Last post
      Powered by Dazdata MDS | 武汉达之云计算有限公司