使用 DRY LookML 最大限度地提高代码的可重用性:为复杂计算定义可重复使用的衡量指标

在 LookML 中定义复杂计算时,将其分解为多个涉及更简单计算的中间步骤会很有帮助。通过创建中间测量,您可以使计算更易于阅读、更易于维护且不易出错,因为您只需确保每个中间计算在一个位置都正确无误。

本页面提供了一个示例,说明如何通过定义中间措施将复杂计算分解为更小、更易于管理的步骤,从而提高 LookML 中计算的可读性和可维护性。

所需要素

前提条件

示例:将复杂计算分解为中间测量值

假设您有一家在线销售产品的公司,您想要定义用于计算总利润和股东股息的措施。要做到这一点,一种方法是定义两个测量:total_profit 测量和 shareholder_dividends 测量,如下所示:


measure: total_profit {
  type: number
  sql: SUM(${orders.sale_price}) - SUM(${employees.salary}) - SUM(${products.cost}) ;;
}

measure: shareholder_dividends
  description: "We give shareholders 60% of our total profits."
  type: number
  sql: 0.6 * (SUM(${orders.sale_price}) - SUM(${employees.salary}) - SUM(${products.cost})) ;;

在此示例中,计算 SUM(${orders.sale_price}) - SUM(${employees.salary}) - SUM(${products.cost}) 在两个测量的 sql 参数中都重复使用了。如果您需要更新此计算的定义(例如更正错误),则必须手动更新这两个测量的计算。

您可以在 shareholder_dividends 测量的计算中重复使用 total_profit 测量,使这些测量定义更易于维护:


measure: total_profit {
  type: number
  sql: SUM(${orders.sale_price}) - SUM(${employees.salary}) - SUM(${products.cost}) ;;
}

measure: shareholder_dividends
  description: "We give shareholders 60% of our total profits."
  type: number
  sql: 0.6 * ${total_profit} ;;

您可能希望将 total_profit 中的计算分解为更简单的测量,以便在其他计算中重复使用。例如,您可以创建名为 total_salestotal_revenuetotal_costtotal_salarytype: sum 测量:


measure: total_sales {
  hidden: yes
  type: sum
  sql: ${orders.sale_price} ;;
}

measure: total_revenue {
  hidden: yes
  type: number
  sql: ${total_sales} ;;
}

measure: total_cost {
  hidden: yes
  type: sum
  sql: ${products.cost} ;;
}

measure: total_salary {
  hidden: yes
  type: sum
  sql: ${employees.salary} ;;
}

然后,您可以重复使用您按如下方式定义的中间字段:


measure: total_expenses {
  type: number
  sql: ${total_cost} + ${total_salary} ;;
}

measure: total_profit {
  type: number
  sql: ${total_revenue} - ${total_expenses} ;;
}

measure: shareholder_dividends {
  description: "We give shareholders 60% of our total profits."
  type: number
  sql: 0.6 * ${total_profit} ;;
}

虽然您定义了更多测量,但这些中间测量可以在其他计算中重复使用,并且它更容易更正错误或对多个测量中使用的计算进行任何更改。