指标
关于指标¶
指标是对表的聚合,该聚合支持零个或多个维度。一些指标示例包括:
- 活跃用户数
- 月收入
在v1.0中,dbt支持将指标定义作为一种新的节点类型。与曝光一样,指标在有向无环图(DAG)中显示为节点,可以在YAML文件中表示。在dbt项目中定义指标将关键业务逻辑编码在经过测试的版本控制代码中。此外,您可以将这些指标定义公开给下游工具,从而提高指标报告的一致性和准确性。
定义指标的好处¶
在下游工具中使用指标规范
dbt的编译上下文可以通过graphic.metrics 变量访问指标。清单工件包括下游元数据消耗的指标。
查看并选择相关性
与曝光一样,您可以看到汇总到指标中的所有内容(dbt-ls-s+metric:*),并在dbt文档中可视化它们。有关详细信息,请参阅“指标:查询方法”

定义指标¶
您可以在嵌套在metrics:下的.yml文件中定义指标。指标名称必须:
- 仅包含字母、数字和下划线(不包含空格或特殊字符)
- 以字母开头
- 包含不超过250个字符
对于带有标题大小写、空格和特殊字符的简短的个性化名称,请使用label属性。有关如何定义和构建指标标准的更多示例和指南,请点击此处。.
定义示例¶
# models/marts/product/schema.yml
version: 2
models:
- name: dim_customers
...
metrics:
- name: rolling_new_customers
label: New Customers
model: ref('dim_customers')
[description](description): "使用该产品的付费客户的14天滚动计数"
calculation_method: count_distinct
expression: user_id
timestamp: signup_date
time_grains: [day, week, month, quarter, year]
dimensions:
- plan
- country
window:
count: 14
period: day
filters:
- field: is_paying
operator: 'is'
value: 'true'
- field: lifetime_value
operator: '>='
value: '100'
- field: company_name
operator: '!='
value: "'Acme, Inc'"
- field: signup_date
operator: '>='
value: "'2020-01-01'"
# general properties
[config](resource-properties/config):
enabled: true | false
treat_null_values_as_zero: true | false
[meta](resource-configs/meta): {team: Finance}
注意
您不能在ephemeral 模型上定义指标.要定义指标,物化必须在数据仓库中具有表示形式。
可用的属性¶
指标可以有许多已声明的 属性 ,这些属性定义了指标的各个方面。参阅属性和配置的更多信息。
| 字段 | 描述 | 示例 | 是否必须? |
|---|---|---|---|
| name | 指标的唯一标识 | new_customers | yes |
| model | 提供该指标的Dbt模型 | dim_customers | yes (no for derived metrics) |
| label | 指标的简写或指标的标签 | New Customers | yes |
| description | 指标的长格式、具有可读性的描述信息 | The number of customers who.... | no |
| calculation_method | 应用于表达式的计算方法(聚合或派生) | count_distinct | yes |
| expression | 要聚合/计算的表达式 | user_id, cast(user_id as int) | yes |
| timestamp | 指标基于时间组件 | signup_date | yes |
| time_grains | 可以评估指标的一个或多个“颗粒”。有关详细信息,请参阅“自定义日历”部分。 | [day, week, month, quarter, year] | 1.4 no / 1.3 yes |
| dimensions | 用于对指标进行分组或筛选的维度列表 | [plan, country] | no |
| window | 用于在一个时间窗口内进行聚合的词典。用于滚动指标,如14天滚动平均值。可接受的期限为:[day,week,month, year, all_time] |
{count: 14, period: day} | no |
| filters | 计算指标之前要应用的筛选器列表 | 参阅下方 | no |
| config | 计算指标的可选配置 | {treat_null_values_as_zero: true} | no |
| meta | 任意key/value存储 | {team: Finance} | no |
可用的计算指标¶
应用于表达式的计算方法(聚合指标或派生指标)。
| 计算指标方法 | 描述 |
|---|---|
| count | 此指标类型将对指定字段应用count聚合 |
| count_distinct | 此指标类型将对指定字段应用count_distinct聚合 |
| sum | 此指标类型将对指定字段应用sum聚合 |
| average | 此指标类型将对指定字段应用average聚合 |
| min | 此指标类型将对指定字段应用min聚合 |
| max | 此指标类型将对指定字段应用max聚合 |
| median | 此指标类型将对指定字段应用median聚合,或者如果median不可用,则使用另一个percentile_cont聚合 |
| derived | 此指标类型定义为1个或多个指标的任何非聚合计算 |
派生指标¶
在v1.2中,增加了对派生指标(以前称为表达式)的支持,这些指标被定义为一个或多个指标的非聚合计算。这方面的一个例子是{{metric(‘total_revenue’)}}”/“{metrics(‘count_of_customers’)}}。
通过定义这些指标,您可以创建以下指标: - 比率 - 减法 - 任意计算
只要两个(或多个)基本指标(包括派生指标)共享指定的时间聚合和维度,这些属性就可以用于任何下游指标。
派生指标的定义示例如下:
# models/marts/product/schema.yml
version: 2
models:
- name: dim_customers
...
metrics:
- name: average_revenue_per_customer
label: Average Revenue Per Customer
description: "The average revenue received per customer"
calculation_method: derived
expression: "{{metric('total_revenue')}} / {{metric('count_of_customers')}}"
timestamp: order_date
time_grains: [day, week, month, quarter, year, all_time]
dimensions:
- had_discount
- order_country
过滤器¶
过滤器应该定义为定义指标术语的字典列表。过滤器使用AND子句进行组合。为了获得更多的控制,用户可以(也应该)在为提供指标的模型中包含复杂的逻辑。
每个定义的筛选器都需要所有三个属性(field, operator, value) .
请注意,value必须在YAML中定义为字符串,因为它将作为字符串的一部分编译成select查询。如果过滤器的值需要在查询中用引号括起来(例如文本或日期),请使用"'嵌套'"引号:
filters:
- field: is_paying
operator: 'is'
value: 'true'
- field: lifetime_value
operator: '>='
value: '100'
- field: company_name
operator: '!='
value: "'Acme, Inc'"
- field: signup_date
operator: '>='
value: "'2020-01-01'"
日历¶
dbt_metrics包包含一个基本日历表它是作为dbt run的一部分创建的。它包含2010年1月1日至2029-12-31年之间的日期。
如果要使用自定义日历,可以将默认日历替换为满足以下要求的任何表:
- 包含一个date_day 列.
- 包含以下列:: date_week, date_month, date_quarter, date_year, 或相等的列.
- 其他日期列需要以date_为前缀,例如4-5-4零售日历日期集的date_4_5_4_month。维度可以有任何名称(请参见以下部分)
要执行此操作,请在dbt_project.yml文件中设置dbt_metrics_calendar_mode变量的值:
日历表中的维度¶
您可能希望按自定义日历表中的维度聚合指标,例如is_weekend。您可以将其包含在宏调用的维度列表中,而无需在指标定义中进行定义。
为此,请在项目级别设置一个名为custom_calendar_dimension_list的列表变量,如下例所示。
配置¶
指标节点现在像其他dbt资源一样接受配置字典。在指标yml本身中指定指标配置,或为dbt_project.yml文件中的指标组指定指标配置。
#models/metrics.yml
version: 2
metrics:
- name: config_metric
label: Example Metric with Config
model: ref(‘my_model’)
calculation_method: count
timestamp: date_field
time_grains: [day, week, month]
config:
enabled: true
接受的指标配置¶
以下是当前接受的指标配置列表:
| 配置项 | 类型 | 可接受值 | 默认值 | 描述 |
|---|---|---|---|---|
enabled |
boolean | True/False | True | 启用或禁用度量节点。禁用时,dbt不会将其视为项目的一部分. |
treat_null_values_as_zero |
boolean | True/False | True | 控制指标的合并行为。默认情况下,coalesce({{field}},0),以返回0而不是null。将此配置设置为False会返回NULL值。 |
查询指标¶
您可以直接在dbt中动态查询指标,并在部署环境中运行作业之前对其进行验证。要查询您定义的指标,您必须具有dbt_metrics包。请参阅安装程序包.
使用以下指标包packages.yml文件中的安装代码,然后运行dbt-deps安装指标包:
使用dbt deps安装包后,请确保运行dbt_metrics_default_calendar模型,因为这是用于查询指标的宏所必需的。有关这方面的更多信息以及其他日历功能,可以在[项目自述]中找到(https://github.com/dbt-labs/dbt_metrics#calendar).
使用metrics.calculate查询指标¶
使用metrics.camputer宏和定义的指标生成SQL语句,该语句运行指标聚合以返回正确的指标数据集。以下示例:
select *
from {{ metrics.calculate(
metric('new_customers'),
grain='week',
dimensions=['plan', 'country']
) }}
支持的输入¶
上面的示例没有显示您可以提供给宏的所有潜在输入。
您可能会发现一些功能,如二次计算,使用起来很复杂。我们建议查看软件包自述文件有关下表中未涵盖的每个输入的更深入信息。
| Input | Example | Description | Required |
|---|---|---|---|
metric('some_metric)', [ metric('some_metric)', metric('some_other_metric)']'metric_name' |
Required | ||
| grain | 'day', 'week', 'month', 'quarter', 'year', 'all_time' |
The time grain that the metric will be aggregated to in the returned dataset | Required |
| dimensions | ['plan','country'] |
The dimensions you want the metric to be aggregated by in the returned dataset | Optional |
| secondary_calculations | [metrics.period_over_period( comparison_strategy="ratio", interval=1, alias="pop_1wk")] |
Performs the specified secondary calculation on the metric results. Examples include period over period calculations, rolling calculations, and period to date calculations. | Optional |
| start_date | '2022-01-01' |
Limits the date range of data used in the metric calculation by not querying data before this date | Optional |
| end_date | '2022-12-31' |
Limits the date range of data used in the metric calculation by not querying data after this date | Optional |
| where | plan='paying_customer' |
A sql statement, or series of sql statements, that alter the final CTE in the generated sql. Most often used to limit the data to specific values of dimensions provided | Optional |
二次计算¶
辅助计算是窗口函数,您可以将其添加到指标计算中,并对一个或多个主要指标执行。
您可以使用它们将值与早期进行比较,计算今年迄今为止的总和,并返回滚动平均值。您可以将自定义的二次计算添加到dbt项目中-有关此方面的更多信息,请参阅包详情。
支持的二次计算包括:
周期到周期:¶
周期间二次计算通过确定两个时间点之间的差异或比率,对所讨论的指标进行计算。输入变量查看在宏中选择的颗粒,确定另一个点。
| Input | Example | Description | Required |
|---|---|---|---|
comparison_strategy |
ratio or difference |
How to calculate the delta between the two periods | Yes |
interval |
1 | Integer - the number of time grains to look back | Yes |
alias |
week_over_week |
The column alias for the resulting calculation | No |
metric_list |
base_sum_metric |
List of metrics that the secondary calculation should be applied to. Default is all metrics selected | No |
截止日期:¶
到目前为止的时间段二次计算对定义的时间段执行聚合,该时间段等于或高于选定的粒度。例如,当您希望在每周粒度指标的同时显示month_to_date值时。
| Input | Example | Description | Required |
|---|---|---|---|
aggregate |
max, average |
The aggregation to use in the window function. Options vary based on the primary aggregation and are enforced in validate_aggregate_coherence(). | Yes |
period |
"day", "week" |
The time grain to aggregate to. One of ["day", "week", "month", "quarter", "year"]. Must be at equal or coarser (higher, more aggregated) granularity than the metric's grain (see Time Grains below). In example grain of month, the acceptable periods would be month, quarter, or year. |
Yes |
alias |
month_to_date |
The column alias for the resulting calculation | No |
metric_list |
base_sum_metric |
List of metrics that the secondary calculation should be applied to. Default is all metrics selected | No |
滚动:¶
滚动二次计算对指标数据集中的多行执行聚合。例如,如果用户选择周粒度并将滚动二次计算设置为4,则返回的值将是所选择的任何聚合类型的滚动4周计算。如果没有提供interval输入,则滚动计算将在所有前面的行上是无边界的。
| Input | Example | Description | Required |
|---|---|---|---|
aggregate |
max, average |
The aggregation to use in the window function. Options vary based on the primary aggregation and are enforced in validate_aggregate_coherence(). | Yes |
interval |
1 | Integer - the number of time grains to look back | No |
alias |
month_to_date |
The column alias for the resulting calculation | No |
metric_list |
base_sum_metric |
List of metrics that the secondary calculation should be applied to. Default is all metrics selected | No |
先前的:¶
上一次二次计算返回行之前指定间隔数的值。
| Input | Example | Description | Required |
|---|---|---|---|
interval |
1 | Integer - the number of time grains to look back | Yes |
alias |
2_weeks_prior |
The column alias for the resulting calculation | No |
metric_list |
base_sum_metric |
List of metrics that the secondary calculation should be applied to. Default is all metrics selected | No |
Developing metrics with metrics.develop¶
在项目中定义指标之前,有时可能需要测试指标的外观。在这些情况下,开发指标允许您在包含的yml中提供单个指标,这样您就可以模拟项目中定义的指标可能是什么样子。
{% set my_metric_yml -%}
{% raw %}
metrics:
-- The name of the metric does not need to be develop_metric
- name: develop_metric
model: ref('fact_orders')
label: Total Discount ($)
timestamp: order_date
time_grains: [day, week, month, quarter, year, all_time]
calculation_method: average
expression: discount_total
dimensions:
- had_discount
- order_country
{% endraw %}
{%- endset %}
select *
from {{ metrics.develop(
develop_yml=my_metric_yml,
metric_list=['develop_metric'],
grain='month'
)
}}
重要提示 - metrics.develow宏的指标值列表输入的是指标值名称本身,而不是calculate宏使用的metric('name')语句。使用上面的示例:
- ✅
['develop_metric'] - ❌
[metric('develop_metric')]
带Metrics.develop的多重/派生指标¶
如果您有一个更复杂的用例,那么开发宏也支持这种行为。唯一需要注意的是,您必须为任何提供的包含派生指标的指标yml包含原始标记。以下示例:
{% set my_metric_yml -%}
{% raw %}
metrics:
- name: develop_metric
model: ref('fact_orders')
label: Total Discount ($)
timestamp: order_date
time_grains: [day, week, month]
calculation_method: average
expression: discount_total
dimensions:
- had_discount
- order_country
- name: derived_metric
label: Total Discount ($)
timestamp: order_date
time_grains: [day, week, month]
calculation_method: derived
expression: "{{ metric('develop_metric') }} - 1 "
dimensions:
- had_discount
- order_country
- name: some_other_metric_not_using
label: Total Discount ($)
timestamp: order_date
time_grains: [day, week, month]
calculation_method: derived
expression: "{{ metric('derived_metric') }} - 1 "
dimensions:
- had_discount
- order_country
{% endraw %}
{%- endset %}
select *
from {{ metrics.develop(
develop_yml=my_metric_yml,
metric_list=['derived_metric']
grain='month'
)
}}
上面的示例将返回一个数据集,该数据集包含指标列表中提供的指标(derived_metric)和父指标(develop_metric)。它不会包含some_other_metric_not_using,因为它没有在指标列表中指定,也没有被指定为所包含指标的父级。
重要警告 - 您必须用双引号将派生指标的expression属性包装起来才能呈现它。例如,expression:“{{metric('development_metric’)}-1。