【问题标题】:Extracting ref and source tables from a dbt model从 dbt 模型中提取 ref 和 source 表
【发布时间】:2022-02-01 08:02:14
【问题描述】:

我在 dbt 中有一个模型,它使用不同的源和参考表。所以我的问题是... 是否可以创建一个宏来从模型中提取所有 ref 和 source 表?让我给你举个例子

我有这个模型:

    select
*

from        {{ ref('x') }}   a
left join   {{ source('landing', 'y') }} ma on a.... = ma....
left join   {{ source('landing', 'z') }} b on a.... = b....

因此,一旦为该模型运行宏,我想获取名称或 ref 和源表。那可能吗?我想在 dbt 中执行此操作,但请告诉我使用 python 是否会更好。

谢谢!

【问题讨论】:

  • 您是说您想要特定模型的依赖项列表吗?所以就像一个打印出 x、y 和 z 的列表?
  • 是的,拜托!这就是我要找的

标签: python sql dbt


【解决方案1】:
-- my_macro.sql

{% macro get_dependencies(model_name) %}
    {% set models = graph.nodes.values() %}

    {% set model = (models | selectattr('name', 'equalto', model_name) | list).pop() %}

    {% do log("sources: ", info=true) %}
    {% set sources = model['sources'] %}
    {% for source in sources %}
    {% do log(source[0] ~ '.' ~ source[1], info=true) %}
    {% endfor %}


    {% do log("refs: ", info=true) %}
    {% set refs = model['refs'] %}
    {% for ref in refs %}
    {% do log(ref[0], info=true) %}
    {% endfor %}

{% endmacro %}

添加此宏后,请尝试使用此...

dbt run-operation get_dependencies --args '{model_name: my_model}'

它会吐出来……

sources:
landing.y
landing.z
refs:
x

按照我目前编写的方式,它将写出任何重复的来源或模型。例如如果您在多个位置有{{ ref('x') }},那么它会多次写入。

refs:
x
x
x

我使用以下有关图形变量的文档将其拼凑在一起。

https://docs.getdbt.com/reference/dbt-jinja-functions/graph

编辑:

这是一种获取唯一来源和参考列表的方法。这不是最漂亮的,但它有效。 (必须有更好的方法来获取唯一列表!)

{% macro get_dependencies(model_name) %}
    {% set models = graph.nodes.values() %}

    {% set model = (models | selectattr('name', 'equalto', model_name) | list).pop() %}
    {% set sources = model['sources'] %}
    {% set refs = model['refs'] %}


    {% do log("sources: ", info=true) %}
    {% set unique_sources = [] %}    
    {% for source in sources if source not in unique_sources %}
        {% do unique_sources.append(source) %}
        {% do log(source[0] ~ '.' ~ source[1], info=true) %}
    {% endfor %}

    {% do log("refs: ", info=true) %}
    {% set unique_refs = [] %}    
    {% for ref in refs if reference not in unique_refs %}
        {% do unique_refs.append(ref) %}
        {% do log(ref[0], info=true) %}
    {% endfor %}

{% endmacro %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2016-05-16
    相关资源
    最近更新 更多