💨
【dbt Docs】Building a dbt Project - Models - Using aliases
Using aliases
Overview
dbtでは、モデル構築時に、 view か table が作られるが、その差のテーブル名は、dbt上のファイル名になる。
aliasを使うことで、ファイル名ではなく別名にすることができる。
Why alias model names?
なんで別名をつけるの?
スキーマ名とテーブル名は、ユーザにわかりやすいほうが使いやすい。適切な名前であれば、利用者にどんなテーブルなのか?が直感的にわかりやすい。カスタムスキーマと組み合わせると、より使いやすいデータウェアハウスを設計できる。
Usage
使い方
以下の通り
| Model | Config | Detabase Identifier |
|---|---|---|
| ga_sessions.sql | なし | "analitics"."ga_sessions" |
| ga_sessions.sql | {{ config(alias=sessions) }} |
"analytics"."sessions" |
となる。
こちらの指定は、.sqlファイルでそれぞれ記載する( dbt_project.ymlではできなさそう)
models/google_analytics/ga_sessions.sql
-- This model will be created in the database with the identifier `sessions`
-- Note that in this example, `alias` is used along with a custom schema
{{ config(alias='sessions', schema='google_analytics') }}
select * from ...
ただし、ref関数で参照する場合は、ファイル名である必要がある
select * from {{ ref('ga_sessions') }}
union all
select * from {{ ref('snowplow_sessions') }}
generate_alias_name
generate_alias_nameマクロにて別名(=Alias)を生成することもできる。
get_custom_alias.sql
{% macro generate_alias_name(custom_alias_name=none, node=none) -%}
{%- if custom_alias_name is none -%}
{{ node.name }}
{%- else -%}
{{ custom_alias_name | trim }}
{%- endif -%}
{%- endmacro %}
Caveats (警告)
Ambiguous detabase identifiers
曖昧なデータベース
aliasを使用すると、重複な名前を持つモデルを誤って作ってしまう可能性がある。
models/snowplow_sessions.sql
{{ config(alias='sessions') }}
select * from ...
select * from ...
このようにしてしまった場合、dbtはエラーを出力する
$ dbt compile
Encountered an error:
Compilation Error
dbt found two resources with the database representation "analytics.sessions".
dbt cannot create two resources with identical database representations. To fix this,
change the "schema" or "alias" configuration of one of these resources:
- model.my_project.snowplow_sessions (models/snowplow_sessions.sql)
- model.my_project.sessions (models/sessions.sql)
Discussion