4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【データ基盤構築/dbt】dbt testでのクエリコストを節約する

Last updated at Posted at 2023-02-26

今回の課題

dbt testコマンドを実行すると、基本的にデータが全量スキャンされ、コストが高いクエリになってしまう。
コストを削減するために、
毎日特定の時間に一度、増分更新が行われているテーブルに対しては、
増分更新が実施されたデータに対してのみ、テストが走る方法調査して実装してみることにした。

※参考:dbtとデータパーティショニングで、大量データを扱う(dbt test)

実装方法

1)dbt modelが走った時間をカラム化する

下記のように_last_dbt_run_atカラムに、dbt modelコマンドが走った日の日付を格納するようにする。

/* model */
select
    *
    , {{ dbt.date_trunc('day', dbt.current_timestamp()) }} as _last_dbt_run_at -- dbt runを実施した日のカラムがtimestamp型で生成される
from
    `テーブル名`

2)_last_dbt_run_atで、test範囲を絞り込む

上記で作成した_last_dbt_run_atカラムを使って、schema.ymlファイルにてtest範囲を絞り込む。
一日一回、増分更新が実施されるので、前日から増分更新で追加されたデータに対して、テストが走るように実装したい。
そこで、下記のように_last_dbt_run_atの日程が、dbt testを実行した日程の前日以降のものとなっているデータに対して、スキャンが走るように記述した。

# schema.yml
version: 2

models:
  - name: [モデル名]
    columns:
      - name: [カラム名]
        tests:
          - not_null:
              config:
                where: "_last_dbt_run_at >= date_sub(date_trunc(current_timestamp(), day), interval 1 day)"

以上のようなかたちで、dbt test時のデータのスキャン量を減らし、クエリのコストの削減を実現した。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?