dbtのaliasでテーブルの名前を変えてみた

はじめに

データアナリティクス事業本部のおざわです。 dbtのaliasの機能を使う機会があったのでご紹介したいと思います。

通常、マテリアライズされたテーブルやビューは、モデルと同じ名前になります。例えばcustomers.sqlというモデルがあって、マテリアライズにtableを指定すればcustomersテーブルができますが、aliasを使うと出力されるテーブルの名前を変更することができます。

使い方

使い方としては非常に簡単でした。ドキュメントにもあるとおり、SQLやyamlファイルに定義します。

SQLファイルに書く場合は、以下のようになります。aliasを指定しなければテーブル名はファイル名と同じga_sessionsになりますが、この場合はaliasで指定したsessionsという名前にしてくれます。

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 ...

以下、同じことをyamlファイルで行っています。

schema.yml

models:
  - name: ga_sessions
    config:
      alias: sessions

なにが嬉しいのか

例えばfinanceとmarketingのスキーマがあり、以下の2つのテーブルを作成したいとします。

finance.customers
marketing.customers

出力するスキーマを分けるには、以下のブログで紹介されているCustom Schemaが使用できます。

通常であればモデル名をcustomersのようにしますが、dbtの決まりとしてプロジェクト内でモデル名を一意にする必要があります。

モデルを格納するディレクトリを分けていても、モデルの名前が重複しているとdbt runの実行時に以下のようなエラーが出ます。

> dbt run        
Compilation Error
  dbt found two models with the name "customers".
  
  Since these resources have the same name, dbt will be unable to find the correct resource
  when looking for ref("customers").
  
  To fix this, change the name of one of these resources:
  - model.my_project.customers (models/finance/customers.sql)
  - model.my_project.customers (models/marketing/customers.sql)

このような場合に、モデルをfinance_customersmarketing_customersのようにしてから、aliasにcustomersを指定します。こうすることでプロジェクト内でモデル名を一意にしながら、出力されるテーブルを同じcustomersにすることができます。

finance_customers.yml

models:
  - name: finance_customers
    config:
      alias: customers

marketing_customers.yml

models:
  - name: marketing_customers
    config:
      alias: customers

おわりに

以上、aliasの使用方法でした。どなたかの参考になれば幸いです。

参考リンク