【问题标题】:How to create table manually or use postgres partition when using dbt?使用dbt时如何手动创建表或使用postgres分区?
【发布时间】:2023-02-20 15:16:40
【问题描述】:

我想使用 dbt 将数据插入到分区表中,但发现不支持 dbt postgres 分区。

通过另一种方式,我在 pre_hook 中创建表和分区,但在运行 dbt 时出现错误“关系‘download_counts_p’已经存在”

有什么建议吗?这是我的 SQL 和 pre_hook 配置

{{ config(
    materialized = 'table',
    indexes = [ ],
    pre_hook=[
        'CREATE TABLE IF NOT EXISTS "download_counts_p" (
                                              "channel_id" int8 NOT NULL,
                                              "product_id" int8 NOT NULL,
                                              "country_code" text NOT NULL,
                                              "year" int2  NULL,
                                              "month" int2 NOT NULL,
                                              "count" int8 NOT NULL,
                                              "count" int8 NOT NULL,
                                              "months" int8 NOT NULL
                                         ) partition by list(country_code)',
        "DO $$
    Declare unique_country_code varchar;
    BEGIN
        FOR unique_country_code IN
            SELECT country_code as unique_country_code FROM download_counts group by country_code

            LOOP
                EXECUTE  format('create table IF NOT EXISTS download_counts_p_%s partition of download_counts_p for values in (''%s'')', upper(unique_country_code), unique_country_code);
            END LOOP;
    END; $$;"]
)}}


select 1

【问题讨论】:

标签: database postgresql dbt


【解决方案1】:

这里发生了一些不同的事情。

  1. 您说得对,dbt 的 postgres 适配器 does not currently support 是分区表的配置。这里的解决方案是创建一个 new materialization 来插入您需要的额外 DDL。您不想在 dbt 中手动编写 DDL——这被认为是一个很大的反模式。您可能还想在 dbt-core(postgres 适配器代码所在的位置)中打开一个问题以提出功能请求
  2. 你的FOR ... LOOP ... END LOOP 钩子真的应该写成它自己的模型,使用 jinja 循环。您可以使用 run_query 宏将数据返回到神社上下文。该页面底部有一个示例,它将查询结果提取到 jinja 上下文中,然后使用 {% for payment_method in results_list %} 循环遍历它们

【讨论】:

    【解决方案2】:

    我遇到了类似的问题并且能够实现我自己 详情https://medium.com/@fmohammad_91999/postgresql-table-partitioning-in-dbt-6d6ed82e90ca

    【讨论】:

    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多