我有一堆 dbt 模型,它们大约 90% 的结构是相同的。这个想法是,这些模型将在 dbt 运行期间组合成一个统一的下游模型。目前我对模型的测试有很多重复。例如
- name: model1
columns:
- name: colA
tests:
- accepted_values:
- values ['a','b']
- name: colB
tests:
- non_null
- name: model2
columns:
- name: colA
tests:
- accepted_values:
- values ['a','b','c']
- name: colB
tests:
- non_null
我想通过重复使用具有较小变化的测试配置来减少 schema.yml 文件中的重复。
到目前为止我已经尝试过
将测试定义为
dbt_project.yml
中的 var,并在schema.yml
中引用它。这可行,但不能有任何变化定义一个返回包含测试配置的 python 列表的宏,并像这样调用该宏
列:“{{ common_tests() }}”
这不起作用,因为我得到 could not render {{ common_tests() }} 'common_tests' is undefined
。
有趣的是,可以在 yaml 文件内的各个测试中使用宏来渲染 yaml,只是不在顶层。
我觉得这里应该有一个简单的解决方案,我只是没有找到它。提前致谢。
最佳答案
如果您不介意在一个 .yml
中定义所有这些模型文件中,您可以为此使用 YAML anchor 。
乔什·德夫林 (Josh Devlin) 写了一篇不错的文章 here :
version: 2
models:
- name: model_one
columns:
- name: id
tests: &unique_not_null
- unique
- not_null
- name: col_a
- name: col_b
- name: model_two
columns:
- name: id
tests: *unique_not_null
- name: col_c
- name: col_d
Josh 的示例显示 tests
上的 anchor 单列的键,但您也可以在 columns
上使用 anchor key 。但这效果不太好,因为即使使用合并运算符( <<
),如果单个测试中存在单个更改,您也需要重复所有内容。没有用于重复列表或列表项的 YAML 等效项,而这正是您在这里所需要的。
关于dbt - 在 DBT 模型之间共享测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73573951/