セマンティックレイヤーで指標を一度だけ定義する

読了まで約58 分分、9 節 節の 8 例 例。

第2026.11.15版 2026年11月19日時点で例が通過 78 例中 78 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.15)から翻訳した。 原文を読む

本章を読み終えると、MetricFlow の YAML 仕様でショップのセマンティックモデルと指標を記述し、本書独自のコンパイラで指標の要求を SQL にコンパイルし、エンティティ結合が行を増殖させないことを示し、会計カレンダーで集計し、MetricFlow が同じ定義を同じ結果にコンパイルすることを確認できるようになる。

第1章では、定義済みの指標を一つ、純売上について取り上げ、その問いに答えた。指標は数行の Python で書かれ、SQL は文字列整形で組み立てられていた。これは、本書が一貫して保つ構図、すなわちモデルが統制された定義を選び、コードが SQL を書くという構図を示すには十分であった。しかし、ショップのチームが、販売しているキャンプ用品やアウトドア用品について尋ねる問いには足りない。経理部門は、2026会計年度の国別の返金率を知りたい。カテゴリマネージャーは、商品カテゴリ別の純売上を知りたい。カテゴリは注文ではなく注文明細にある。マーケティング部門は、チャネル別の平均注文額を知りたい。これらはいずれも結合、粒度、比率のどれかを必要とし、それぞれが、第2章でスキーマだけを頼りにした SQL が誤りを犯した箇所に当たる。行を重複させる結合、スキーマが保持していない定義、1月に始まらない年である。

セマンティックレイヤーは、結合、粒度、比率の背後にある選択を一度だけ書き留めておく場所である。各テーブルを、エンティティ(結合に使えるキー)、ディメンション(グループ化や絞り込みに使えるもの)、指標(人々が求める数値とその規則)によって記述し、指標の要求を SQL にコンパイルする。モデルのコンテキストに業務上の意味を含めると有効だという証拠は乏しい。我々が依拠する唯一のベンチマークは、ある企業の保険スキーマ一つを対象とし、GPT-4 の正答率が SQL テーブルに対しては 16%、業務上の意味を備えたナレッジグラフ層に対しては 54% であったと報告している(Sequeda et al., 2023)。著者らはナレッジグラフのベンダーに所属しており、この研究が扱ったのは一つのスキーマと一つのモデルにすぎない。したがって、これは意味が役に立つことを示す兆候として読むべきであり、読者が実際に得られる倍率として読むべきではない。

本章では、MetricFlow の YAML でショップのセマンティックレイヤーを構築し、本書独自の小さなコンパイラである lib/semantic.py でコンパイルし、同じファイルを読み込む MetricFlow 0.214.0 と照合して検証する。MetricFlow は dbt Labs が保守しているセマンティックレイヤーであり、2025年10月14日からバージョン 0.209.0 以降が Apache 2.0 ライセンスで提供されている(dbt Labs; PyPI)。本書が独自のコンパイラを用いるのは、要求から SQL までの各段階を読者がすべて読めるようにするためであり、また、例が我々が変更したときにしか変わらないようにするためである。

この部分はまだ翻訳されていないため、英語で表示している。

Describe each table as a semantic model

最終変更:版2026.11.12

A semantic model is one table described for the layer: which table it reads, the entities it holds, the dimensions it offers and the time dimension its numbers are counted on. An entity is a key with a type. A primary entity is unique in its table, so other tables can join to it many rows to one. A foreign entity is a key that points at another table's primary entity, and it repeats. That one word, primary or foreign, is what lets a layer join tables without repeating rows, so it is the most important thing you declare. The shop's whole layer lives in examples/data/semantic/: one file per semantic model, one metrics.yml, and one project_configuration.yml, which names the time spine, a table with one row per day.

Older MetricFlow specs have a third kind of element, the measure: an aggregation declared on the semantic model, which a metric then names. dbt's documentation for its spec in dbt v1.12 and later says "Measures are deprecated in the new spec and are replaced with simple metrics" (dbt Labs). The shop's YAML follows that direction. Each simple metric names its semantic model, its aggregation and its expression itself, in the standalone document shape that MetricFlow's own parser reads: one semantic_model: or metric: per YAML document, and tables named by node_relation. Here is the shop's orders model, shortened, and net revenue, the metric chapter 1 defined in Python:

semantic_model:
  name: orders
  node_relation:
    schema_name: analytics
    alias: fct_orders
  defaults:
    agg_time_dimension: order_date
  entities:
    - name: order
      type: primary
      expr: order_id
    - name: customer
      type: foreign
      expr: customer_id
  dimensions:
    - name: order_date
      type: time
      expr: order_date_local
      type_params:
        time_granularity: day
    - name: region
      type: categorical
---
metric:
  name: net_revenue
  type: simple
  type_params:
    expr: net_revenue_eur
    metric_aggregation_params:
      semantic_model: orders
      agg: sum
  filter: "{{ Dimension('order__status') }} != 'cancelled'"

The orders model's time dimension is order_date_local, the order's local business day, so every metric on it counts days the way finance does. Net revenue's rule for which orders count, the one chapter 1's schema-only SQL missed, is the metric's filter. metrics.yml also holds net revenue's description, word for word as chapter 1 wrote it, and chapter 1's lib/metrics.py reads its table, aggregate and condition from this YAML, so the definition exists in one place.

Parsing won't reveal a wrong declaration, so the code loads the layer and checks its definitions against the warehouse: every expression must run, and every primary entity must be unique in its table. It repeats the check on a copy with one mistake, in which the order lines declare order as their primary entity.

load-semantic-models.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Load the shop's semantic layer from YAML, list what each semantic model declares, and check it against the warehouse."""from dataclasses import replacefrom lib.semantic import Entity, SemanticLayer, loadfrom lib.warehouse import connectlayer = load()                   # reads examples/data/semantic/*.yml and validates the definitionsprint(f"semantic models: {len(layer.semantic_models)}")print(f"metrics: {len(layer.metrics)}")for model in layer.semantic_models.values():    entities = ", ".join(f"{e.name} ({e.type})" for e in model.entities.values())    print(f"{model.name}: {model.table}; entities: {entities}; dimensions: {', '.join(model.dimensions) or 'none'}")metric = layer.metrics["net_revenue"]print(f"net_revenue: {metric.agg} of {metric.expr} in {metric.semantic_model}, where {metric.filter}")con = connect()print(f"problems in the shop's definitions: {len(layer.check(con))}")# A layer with one mistake: the lines declare `order` as their primary entity, as if each order had one line.lines = layer.semantic_models["order_lines"]wrong = replace(lines, entities={"order": Entity("order", "primary", "order_id"),                                 "product": lines.entities["product"]})for problem in SemanticLayer({"order_lines": wrong}, {}, layer.time_spine).check(con):    print(f"problem: {problem}")
出力python load-semantic-models.py
semantic models: 5
metrics: 10
customers: analytics.dim_customers; entities: customer (primary); dimensions: first_order_date, region, country
order_lines: semantic.order_lines; entities: order_line (primary), order (foreign), product (foreign); dimensions: order_date
orders: analytics.fct_orders; entities: order (primary), customer (foreign); dimensions: order_date, region, country, channel, status
products: analytics.dim_products; entities: product (primary); dimensions: product_name, category, subcategory
refunds: semantic.refunds; entities: refund (primary), order (foreign); dimensions: refund_date, order_date, reason
net_revenue: sum of net_revenue_eur in orders, where {{ Dimension('order__status') }} != 'cancelled'
problems in the shop's definitions: 0
problem: order_lines: primary entity 'order' repeats in 23,215 rows

The shop has 5 semantic models and 10 metrics, and the check finds 0 problems in them. The mistaken copy fails it: order_lines: primary entity 'order' repeats in 23,215 rows. An order has several lines, so order_id repeats in the lines table, and a layer that believed it unique would join orders to lines as if each order had one line. Parsing the YAML can't find this, because the file is valid. Only the data can, which is why check() counts duplicates. Two of the semantic models, and the time spine, read views in a third schema of the warehouse, semantic, which this chapter adds; the fiscal calendar section and the production section say why.

Working rule: Declare one semantic model per table, mark an entity primary only where it's unique, and check the declarations against the data whenever the warehouse or the YAML changes. Write simple metrics without measures, naming their model and aggregation, unless your MetricFlow version or your dbt project still requires measures.

この部分はまだ翻訳されていないため、英語で表示している。

Compile a metric request to SQL

最終変更:版2026.11.15

With the shop's definitions loaded, the layer's job is to turn a request into SQL. A metric request names the metrics, the dimensions to group by and the filters, and optionally an order and a limit. It holds names, not SQL, so everything in it can be checked against the definitions before anything runs. The compiler then finds each dimension's column, adds the joins and the metric's own filter, and writes the aggregate.

The book's compiler builds the query as a sqlglot expression tree rather than as text. sqlglot is a Python library that parses, builds and translates SQL. Building a tree has two consequences. A filter value becomes a literal node in the tree, so text inside it can't change the query's structure. And the same tree can be written in another warehouse's dialect, which the dialect subsection uses.

Dimension names follow MetricFlow's convention, so a request reads the same in either tool:

Name What it reaches
order__region region in the model whose primary entity is order
order__customer__region region of the order's customer, two joins away
metric_time__month the metric's own time dimension, by month
metric_time__fiscal_quarter a fiscal quarter from the time spine, a custom grain (fiscal section)

Chapter 1's question is the first test: golden question gq-002 asks, "What was net revenue in each region in March 2026?" As a request, it is net_revenue grouped by order__region and filtered to March 2026. The code prints the request and its SQL, runs it, and checks the answer against the golden result. Then it sends a filter value holding SQL of its own, and asks for a dimension the layer doesn't define.

compile-net-revenue.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Compile one metric request to SQL with the book's semantic layer, run it, and check it against the golden answer. The printed `matches golden: yes` line is the fact the prose states."""from lib.golden import golden_result, load_golden, results_matchfrom lib.semantic import MetricRequest, SemanticError, loadfrom lib.warehouse import connectlayer, con = load(), connect()question = next(q for q in load_golden() if q.question_id == "gq-002")print(f"question: {question.question}")request = MetricRequest(metrics=("net_revenue",), group_by=("order__region",),                        filters={"metric_time__month": "2026-03"})  # the compiler turns this text month into a date literal, compared with a date castprint(f"request: {request}")print(layer.sql(request))answer = layer.query(con, request)print(answer.show())matches = results_match(answer.rows, golden_result(con, question))assert matches, "gq-002 must match its golden result"print(f"matches golden: {'yes' if matches else 'no'}")# A filter value becomes a literal in the expression tree, so text in it can't change the query.hostile = MetricRequest(("net_revenue",), filters={"order__region": "EMEA' OR '1'='1"})condition = layer.compile(hostile).args["where"].sql(dialect="duckdb")print(f"hostile filter compiles to: {condition}")print(f"rows for the hostile value: {layer.query(con, hostile).rows}")# A name the layer doesn't define is refused before any SQL exists, with what the metric can use.try:    layer.compile(MetricRequest(("net_revenue",), ("order__colour",)))except SemanticError as e:    print(f"refused: {e}")
出力python compile-net-revenue.py
question: What was net revenue in each region in March 2026?
request: MetricRequest(metrics=('net_revenue',), group_by=('order__region',), filters={'metric_time__month': '2026-03'}, order_by=(), limit=None)
SELECT
  orders.region AS order__region,
  SUM(orders.net_revenue_eur) AS net_revenue
FROM analytics.fct_orders AS orders
WHERE
  orders.status <> 'cancelled'
  AND CAST(DATE_TRUNC('MONTH', CAST(orders.order_date_local AS DATE)) AS DATE) = CAST('2026-03-01' AS DATE)
GROUP BY
  orders.region
ORDER BY
  order__region ASC
order__region  net_revenue
AMER           51,762.14
APAC           35,296.93
EMEA           63,023.76
matches golden: yes
hostile filter compiles to: WHERE orders.status <> 'cancelled' AND orders.region = 'EMEA'' OR ''1''=''1'
rows for the hostile value: ((None,),)
refused: unknown dimension 'order__colour'; 'net_revenue' can use: metric_time__day, metric_time__week, metric_time__month, metric_time__quarter, metric_time__year, metric_time__fiscal_year, metric_time__fiscal_quarter, customer__country, customer__first_order_date, customer__region, order__channel, order__country, order__order_date, order__region, order__status

The SQL reads one table, analytics.fct_orders, applies the metric's filter on cancelled orders, truncates the local business day to its month and groups by region. It's what an analytics engineer would write by hand, and it matches the golden result for gq-002. The month is written as a date and compared with a date cast, so the comparison doesn't depend on how a warehouse compares text.

The hostile value doesn't change the query. It compiles to WHERE orders.status <> 'cancelled' AND orders.region = 'EMEA'' OR ''1''=''1': one string literal, its quotes doubled, compared with orders.region. No region has that name, so the query returns one row with an empty total. Chapter 1's metric passed values as query parameters for the same reason; a tree of literals does the same job and still lets the query be translated to another dialect.

What a request can't name matters as much. A request for a metric or dimension that isn't defined fails before any SQL exists. A request for order__colour ends in a SemanticError that names the unknown dimension and lists every dimension net revenue can use, from metric_time__day to order__status. That error is what an agent sees when it asks for something the layer doesn't hold, and chapter 6 builds on it.

Working rule: Let the agent, and every other client, send metric requests, never SQL fragments. Resolve every name in a request against the definitions, build the query as a tree with values as literals, and show the SQL with every answer so a person can read what ran. Accept a raw SQL filter only from the people who maintain the layer, never from a model.

この部分はまだ翻訳されていないため、英語で表示している。

Join through entities so sums can't fan out

最終変更:版2026.11.15

The compiled request read one table. Many questions need two. A fan-out happens when a join matches each row of one table to several rows of another, so a sum over the joined rows counts each value of the first table several times. A semantic layer prevents it with the entity types: it joins from a metric's table only to a table where the entity is primary, many rows to one, so each row of the metric's table matches at most one row. MetricFlow's documentation lists a join from a primary to a foreign entity as "Fan-out (Not allowed)" and allows at most two hops (dbt Labs). The book's compiler applies the same two rules.

The shop's case is a category manager's question: net revenue by product category in 2025. Net revenue is summed per order, in analytics.fct_orders, and a product's category is reached through the order lines, several per order. The layer refuses net_revenue by product__category. A hand-written join runs beside that refusal, since it returns a number without error, and the line-level metric is asked for instead.

entity-join-no-fanout.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Ask for net revenue by product category: the layer refuses the fan-out join and points to a line-level metric. The printed `inflated by` and `difference from net revenue` lines are the facts the prose states."""from lib.semantic import FanOutError, MetricRequest, loadfrom lib.warehouse import connectlayer, con = load(), connect()in_2025 = {"metric_time__year": 2025}try:    layer.sql(MetricRequest(("net_revenue",), ("product__category",), in_2025))except FanOutError as e:    print(f"refused: {e}")# What a hand-written join does with the same question: each order's revenue repeats once per line.(joined,), = con.execute("""    SELECT sum(o.net_revenue_eur) FROM analytics.fct_orders AS o    JOIN analytics.fct_order_lines AS l USING (order_id)    WHERE o.status <> 'cancelled' AND year(o.order_date_local) = 2025""").fetchall()(total,), = layer.query(con, MetricRequest(("net_revenue",), filters=in_2025)).rowsprint(f"net revenue, 2025: {total:,.2f}")print(f"summed over the joined lines: {joined:,.2f}")print(f"inflated by: {joined / total - 1:.0%}")request = MetricRequest(("line_net_revenue",), ("product__category",), in_2025, order_by=("-line_net_revenue",))  # a leading minus sorts descending, so the largest category prints firstprint(layer.sql(request))answer = layer.query(con, request)print(answer.show())by_category = sum(row[1] for row in answer.rows)print(f"categories add up to: {by_category:,.2f}")print(f"difference from net revenue: {abs(by_category - total):,.2f}")
出力python entity-join-no-fanout.py
refused: 'net_revenue' is summed per order, but 'product' is reached through 'order_lines', which has many rows per order; each order would count once per row. Use a metric defined on 'order_lines': line_net_revenue, units_sold
net revenue, 2025: 1,651,527.86
summed over the joined lines: 5,573,978.43
inflated by: 238%
SELECT
  products.category AS product__category,
  SUM(order_lines.net_amount_eur) AS line_net_revenue
FROM semantic.order_lines AS order_lines
LEFT JOIN analytics.dim_products AS products
  ON order_lines.product_id = products.product_id
LEFT JOIN analytics.fct_orders AS orders
  ON order_lines.order_id = orders.order_id
WHERE
  orders.status <> 'cancelled'
  AND CAST(DATE_TRUNC('YEAR', CAST(order_lines.order_date_local AS DATE)) AS DATE) = CAST('2025-01-01' AS DATE)
GROUP BY
  products.category
ORDER BY
  line_net_revenue DESC
product__category  line_net_revenue
Sleeping bags      279,693.27
Backpacks          246,002.99
Tents              230,502.32
Footwear           216,840.39
Navigation         212,322.26
Cooking            202,007.56
Clothing           178,584.24
Lighting           85,573.93
categories add up to: 1,651,526.96
difference from net revenue: 0.90

The layer refuses the request and says why: 'net_revenue' is summed per order, but 'product' is reached through 'order_lines', which has many rows per order; each order would count once per row. Use a metric defined on 'order_lines': line_net_revenue, units_sold. The hand-written join shows what the refusal prevents. Net revenue in 2025 is 1,651,527.86 euros. Summed over the orders joined to their lines, the same revenue comes to 5,573,978.43, inflated by 238%, because each order counts once for each of its lines. Nothing in that query fails, and nothing in its result says it's wrong.

line_net_revenue is net revenue counted on the lines themselves, in the order_lines semantic model, with net revenue's rule on cancelled orders. Its SQL joins the lines to products and to orders, both many rows to one, so no line repeats. The categories add up to 1,651,526.96 euros, 0.90 away from net revenue. That gap is rounding, not fan-out: the warehouse rounds each line's amount and each order's total to the cent separately, and over a year of lines the cents add up.

When a request needs numbers from two tables, a layer doesn't join the tables first. It aggregates each metric in its own table, then joins the aggregated results on the dimensions they share; MetricFlow uses full outer joins for that step (dbt Labs), and so does the book's compiler. Each sum is complete before any join, so no join can repeat its rows.

The protection holds only as far as the declarations are true. Declare the lines' order entity primary, as the loading example did on purpose, and the layer would join orders to lines without complaint.

Working rule: Declare entities so that every join the layer makes is many rows to one, and let the layer refuse the rest. When a question needs a number on a finer table, such as revenue by product, define the metric on that table rather than reaching it through a join. Check that primary entities are unique in the data, because a wrong declaration turns the protection off.

単純なメトリクスから比率メトリクスと派生メトリクスを作る

最終変更:版2026.11.15

行単位の売上のような単純なメトリクスは、1つのテーブルの1つの列を集計する。しかし、求められる数値の多くは2つのメトリクスから作られる。返金率や平均注文額がその例である。比率メトリクスは、あるメトリクスを別のメトリクスで割ったものであり、派生メトリクスは、複数のメトリクスを式で組み合わせたものである。重要なのは演算の順序である。比率とは、グループごとに、分子の合計を分母の合計で割ったものであり、行ごとの比率の平均ではない。MetricFlow は、分子と分母を別々のサブクエリで計算し、共通のディメンションで結合してから割り算を行う(dbt Labs)。

このショップの経理チームは、ゴールデンクエスチョン gq-028 で返金率を定義している。対象期間に行われ、キャンセルされなかった注文について、返金額(ユーロ)を同じ注文の総売上で割ったものである。この文には2つの選択が隠れている。1つ目は、返金は代金が戻った日ではなく注文日に帰属させることである。そのため分子は order_refunds であり、これは注文の現地日で数えるメトリクスである。返金日で数える refunds は、別の問いに答えるものである。2つ目は、分母が純売上ではなく総売上であることである。返金は税込みで顧客に請求した金額を払い戻すものであり、総売上は税を含み、純売上は税を含まない。したがって、両辺を同じユーロ建てで測れるのは総売上だけである。純売上を分母にすると、全額返金された注文の返金率は100%を超えてしまう。本書では、用語集や検証済みクエリも含め、この1つの定義を一貫して用いる。分子はキャンセル済み注文のルールを入力フィルタとして持ち、gross_revenue はそれを自身の定義の中に持つ。こうして両辺がそれぞれこのルールを適用する。

この例が重要なのは、誘惑的な版があるからである。注文ごとの返金率を地域ごとに平均する方法は、正しそうに見えるが、正しくない。その隣に、この例がコンパイルする、レイヤーによる2026会計年度の返金率を並べて示す。

refund-rate-metric.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""A ratio metric divides two separately aggregated sums, and averaging per-order ratios gives a different number. The printed `matches golden: yes` lines are the facts the prose states."""from lib.golden import golden_result, load_golden, results_matchfrom lib.semantic import MetricRequest, loadfrom lib.warehouse import connectlayer, con = load(), connect()fiscal_2026 = {"metric_time__fiscal_year": 2026}  # the fiscal year runs February to January, named for the year it ends inrequest = MetricRequest(("refund_rate",), ("order__region",), fiscal_2026)print(layer.sql(request))for region, rate in layer.query(con, request).rows:    print(f"refund rate, {region}: {rate:.2%}")# The tempting shortcut: each order's refunds over its gross revenue, averaged per region.for region, rate in con.execute("""    SELECT o.region, avg(coalesce(r.refunded, 0) / o.gross_revenue_eur)    FROM analytics.fct_orders AS o    JOIN analytics.dim_date AS d ON d.date_day = o.order_date_local    LEFT JOIN (SELECT order_id, sum(amount_eur) AS refunded FROM analytics.fct_refunds GROUP BY order_id) AS r        USING (order_id)    WHERE o.status <> 'cancelled' AND d.fiscal_year = 2026    GROUP BY o.region ORDER BY o.region""").fetchall():    print(f"average of per-order rates, {region}: {rate:.2%}")golden = {q.question_id: q for q in load_golden()}top = layer.query(con, MetricRequest(("refund_rate",), ("order__country",), fiscal_2026, ("-refund_rate",), 1))  # a leading minus sorts descending; the limit keeps the top rowprint(f"highest refund rate: {top.rows[0][0]}")matches = results_match([top.rows[0][:1]], golden_result(con, golden['gq-028']))assert matches, "gq-028 must match its golden result"print(f"gq-028 matches golden: {'yes' if matches else 'no'}")average = layer.query(con, MetricRequest(("average_order_value",), ("order__region",), {"metric_time__month": "2026-03"}))print(average.show())matches = results_match(average.rows, golden_result(con, golden['gq-009']))assert matches, "gq-009 must match its golden result"print(f"gq-009 matches golden: {'yes' if matches else 'no'}")
出力python refund-rate-metric.py
WITH order_refunds AS (
  SELECT
    orders.region AS order__region,
    SUM(refunds.amount_eur) AS order_refunds
  FROM semantic.refunds AS refunds
  LEFT JOIN analytics.fct_orders AS orders
    ON refunds.order_id = orders.order_id
  LEFT JOIN semantic.calendar AS calendar
    ON calendar.date_day = refunds.order_date_local
  WHERE
    orders.status <> 'cancelled' AND calendar.fiscal_year = 2026
  GROUP BY
    orders.region
), gross_revenue AS (
  SELECT
    orders.region AS order__region,
    SUM(orders.gross_revenue_eur) AS gross_revenue
  FROM analytics.fct_orders AS orders
  LEFT JOIN semantic.calendar AS calendar
    ON calendar.date_day = orders.order_date_local
  WHERE
    orders.status <> 'cancelled' AND calendar.fiscal_year = 2026
  GROUP BY
    orders.region
)
SELECT
  COALESCE(order_refunds.order__region, gross_revenue.order__region) AS order__region,
  order_refunds.order_refunds / NULLIF(gross_revenue.gross_revenue, 0) AS refund_rate
FROM order_refunds
FULL OUTER JOIN gross_revenue
  ON gross_revenue.order__region = order_refunds.order__region
ORDER BY
  order__region ASC
refund rate, AMER: 7.11%
refund rate, APAC: 6.02%
refund rate, EMEA: 8.45%
average of per-order rates, AMER: 7.77%
average of per-order rates, APAC: 6.78%
average of per-order rates, EMEA: 8.38%
highest refund rate: NL
gq-028 matches golden: yes
order__region  average_order_value
AMER           300.94
APAC           291.71
EMEA           272.83
gq-009 matches golden: yes

SQL は入力ごとに1つの部分を持つ。order_refunds は、注文に結合した返金を、注文を基準にフィルタおよび日付付けして合計する。gross_revenue は注文を合計する。外側のクエリは2つを地域で結合して割り算を行う。このとき NULLIF を用いることで、売上のない地域ではエラーではなく、比率なしとなる。EMEA の返金率は 8.45%、AMER は 7.11%、APAC は 6.02% である。

注文ごとの比率の平均は、異なる数値を与える。AMER では 7.77% であり、レイヤーの 7.11% とは異なる。EMEA では 8.38% であり、8.45% とは異なる。この方法は、小さな注文の返金を大きな注文の返金と同じ重みで扱うため、典型的な注文のうち返金される割合を答えることになるが、それは誰も尋ねていない問いである。ここでは AMER と APAC が上がり、EMEA が下がるため、実際の金額が示すよりも地域間の差が小さく見える。

国別で返金率が最も高いのは NL であり、これがゴールデンクエスチョン gq-028 の期待する答えである。平均注文額は派生メトリクスであり、net_revenue / kept_orders で表される。ここで kept_orders は、キャンセル済み注文のルールを入力フィルタとして適用した orders メトリクスである。このショップは、キャンセル済みの注文を含めて注文を数えるが、売上を割るときはキャンセル済みを除いた注文数を使う。派生メトリクスは、この2つの定義を両方とも保持する。2026年3月について地域別に集計すると、ゴールデンクエスチョン gq-009 の期待する平均値が得られる。

実践ルール: あらゆる比率を2つのメトリクスの比として定義し、各辺を個別に集計してからグループごとに割る。各辺がどの時間ディメンションで数えられるかを書き留め、各辺がそのフィルタを、自身の定義の中か入力フィルタとして適用していることを確認する。読み手がそれを知っていることに頼ってはならない。式が1回の割り算を超える場合は派生メトリクスを使い、その入力は単独でクエリできる単純なメトリクスにしておく。

会計カレンダーをタイムスパインに置く

最終変更:版2026.11.15

ショップのレイヤーのすべての指標は時間ディメンション上で集計され、質問の多くは期間を指定する。レイヤーは、月・四半期・年といった標準的な粒度については、日付を切り捨てることで処理する。会計期間はこの方法では計算できない。会計期間は、ビジネスが定めた日から始まるためである。MetricFlow は、この両方をタイムスパインを通じて処理する。タイムスパインは1日1行のテーブルであり、時間に基づくすべての指標が、少なくとも日次の粒度で必要とする。fiscal_year のようなカスタム粒度は、各日がどの期間に属するかを示すタイムスパインの列である(dbt Labs)。

ショップの会計年度は2月1日に始まり、終わる年の名前で呼ばれる。したがって、2026会計年度は2025年2月1日から2026年1月31日までである。ウェアハウスの analytics.dim_date は fiscal_year と fiscal_quarter を保持しているが、その四半期は1から4までの数であり、毎年繰り返される。カスタム粒度は1つの期間を指し示さなければならないため、ビュー semantic.calendar は各四半期に 2026-Q1 のように年を付けてラベル付けし、プロジェクト設定は fiscal_year と fiscal_quarter をそのビューのカスタム粒度として宣言する。以後、requests は metric_time__fiscal_quarter でグルーピングできる。

純売上を会計四半期とカレンダー四半期でグルーピングすると、年が2月に始まる場合に2つのカレンダーがどれほどずれるかがわかる。会計年度の第1四半期に関する2つのゴールデンクエスチョンで、この確認を締めくくる。

fiscal-quarter-grain.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Group net revenue by fiscal quarter, a custom grain from the time spine, and by calendar quarter, a standard one. The printed `matches golden: yes` lines are the facts the prose states."""from datetime import datefrom lib.golden import golden_result, load_golden, results_matchfrom lib.semantic import MetricRequest, loadfrom lib.warehouse import connectlayer, con = load(), connect()fiscal = MetricRequest(("net_revenue",), ("metric_time__fiscal_quarter",), {"metric_time__fiscal_year": 2026})print(layer.sql(fiscal))fiscal_answer = layer.query(con, fiscal)print(fiscal_answer.show())calendar = MetricRequest(("net_revenue",), ("metric_time__quarter",), {"metric_time__year": 2025})  # standard grain: truncates the date to the calendar quartercalendar_answer = layer.query(con, calendar)print(calendar_answer.show())print(f"fiscal 2026-Q1, February to April 2025: {dict(fiscal_answer.rows)["2026-Q1"]:,.2f}")print(f"calendar 2025 Q1, January to March 2025: {dict(calendar_answer.rows)[date(2025, 1, 1)]:,.2f}")golden = {q.question: q for q in load_golden()}for text, request in [    ("What was net revenue in the first quarter of fiscal year 2026?",     MetricRequest(("net_revenue",), filters={"metric_time__fiscal_quarter": "2026-Q1"})),    ("What was net revenue in each region in the first quarter of fiscal year 2027?",     MetricRequest(("net_revenue",), ("order__region",), {"metric_time__fiscal_quarter": "2027-Q1"})),]:    question = golden[text]    answer = layer.query(con, request)    matches = results_match(answer.rows, golden_result(con, question))    assert matches, f"{question.question_id} must match its golden result"    print(f"{question.question_id} matches golden: {'yes' if matches else 'no'}")
出力python fiscal-quarter-grain.py
SELECT
  calendar.fiscal_quarter AS metric_time__fiscal_quarter,
  SUM(orders.net_revenue_eur) AS net_revenue
FROM analytics.fct_orders AS orders
LEFT JOIN semantic.calendar AS calendar
  ON calendar.date_day = orders.order_date_local
WHERE
  orders.status <> 'cancelled' AND calendar.fiscal_year = 2026
GROUP BY
  calendar.fiscal_quarter
ORDER BY
  metric_time__fiscal_quarter ASC
metric_time__fiscal_quarter  net_revenue
2026-Q1                      324,929.25
2026-Q2                      467,081.90
2026-Q3                      420,686.84
2026-Q4                      452,065.73
metric_time__quarter  net_revenue
2025-01-01            302,935.85
2025-04-01            415,495.84
2025-07-01            457,906.36
2025-10-01            475,189.81
fiscal 2026-Q1, February to April 2025: 324,929.25
calendar 2025 Q1, January to March 2025: 302,935.85
gq-010 matches golden: yes
gq-026 matches golden: yes

会計のリクエストは、注文を現地の営業日で semantic.calendar に結合し、カレンダーの四半期ラベルでグルーピングする。2025年のカレンダー四半期は1月1日、4月1日、7月1日、10月1日に始まるのに対し、2026会計年度の第1四半期は2025年2月から4月までであるため、一方のグルーピングの四半期は、他方のどの四半期とも一致しない。2026会計年度の第1四半期の純売上は 324,929.25 ユーロであり、2025年のカレンダー第1四半期(1月から3月)の純売上は 302,935.85 ユーロであった。2つのゴールデンクエスチョンはどちらも一致する。2026会計年度第1四半期の純売上は gq-010、2027会計年度第1四半期の地域別は gq-026 である。

2つの制約がある。MetricFlow は「タイムゾーンの操作を一切行わない」(dbt Labs)ため、現地の営業日は、レイヤーがそれを扱う前にウェアハウスに存在していなければならない。ショップのマートは、各地域のタイムゾーンから order_date_local を構築し、ビューは返金についても同様に追加する。また、同じドキュメントはカスタムカレンダーをプレビュー機能と位置づけており、カスタム粒度でのオフセットや期間比較は提供されない。そのため、会計第1四半期を前年の同じ四半期と比較するには、1回ではなく2回のリクエストが必要になる。

実践ルール: 会計カレンダーや業務カレンダーはすべて、各値が1つの期間を指し示すカスタム粒度としてタイムスパインに置き、リクエストはそれらでグルーピングする。現地の営業日は、レイヤーより前の段階であるマートで構築する。会計期間をまたぐ比較が必要な場合は、使用するレイヤーがカスタム粒度でのオフセットに対応するまで、期間ごとに1回ずつリクエストを実行し、結果をコード上で比較する。

定義を MetricFlow で検証する

最終変更:版2026.11.12

ショップの YAMLが可搬であるといえるのは、本番用のツールがそれを本書のコンパイラと同じように読む場合に限られる。本番では、MetricFlow は通常 dbt プロジェクトの中で、dbt-metricflow パッケージとそのコマンドラインを通して動かされる。このパッケージの概要は、dbt を用いて MetricFlow のセマンティックレイヤーに対してコマンドを実行するものと説明しており、dbt-core を必要とする(PyPI)。本書は定義の検証に MetricFlow 単体、すなわち metricflow パッケージを用いる。これは Apache 2.0 であり、dbt への依存がないため、検証はオフラインで数秒のうちに終わる。MetricFlow は同じファイルを解析して検証し、そのエンジンの explain() は実行されるはずの SQL を返す。Python のエンジンである MetricFlowEngine は、0.x バージョンの内部 API である。0.213.0 の wheel(PyPI)の metricflow/engine/metricflow_engine.py にあるこのクラスの docstring は、保守担当者に向けて「このクラスが安定していると仮定せず、代わりにより安定した API 層を提供する」ようメモを残している。本書は、これに触れる処理をすべて lib/metricflow_bridge.py にまとめ、MetricFlow が DuckDB 上で SQL を実行できるようにする小さなアダプタを添えている。

二つのコンパイラは同じ行を返すはずである。そこで、この例では 8 件のリクエストを検証する。対象は、単純メトリクス、比率メトリクス、派生メトリクス、2 ホップの結合、会計期間の粒度、そして 1 つのテーブル上の二つの時間ディメンションである。各ペアをショップのウェアハウス上で実行し、その行を比較する。この実行では、第 1 章の問いに対する MetricFlow の SQL と、結合の節のリクエストに対する MetricFlow の拒否も出力する。

metricflow-agrees.py Python 3.12.15 · duckdb 2.0.0 · metricflow 0.214.0 · pydantic 2.14.3 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Compile the same requests with MetricFlow and with the book's compiler, run both, and compare the results. The printed `requests that agree` line is the fact the prose states."""from lib.golden import results_matchfrom lib.metricflow_bridge import as_dates, engine, explain_sqlfrom lib.semantic import MetricRequest as Request, loadfrom lib.warehouse import connectcon = connect()layer, mf = load(), engine(con)   # both read examples/data/semantic/*.ymlrequests = [    Request(("net_revenue",), ("order__region",), {"metric_time__month": "2026-03"}),    Request(("net_revenue", "orders"), ("metric_time__fiscal_quarter",), {"metric_time__fiscal_year": 2026}),    Request(("line_net_revenue", "units_sold"), ("product__category",), {"metric_time__year": 2025}),    Request(("units_sold",), ("order__customer__region",), {"metric_time__year": 2025}),    Request(("refund_rate",), ("order__country",), {"metric_time__fiscal_year": 2026}),    Request(("average_order_value",), ("order__channel",), {"metric_time__month": "2026-03"}),    Request(("refunds", "order_refunds"), ("metric_time__month",), {"metric_time__year": 2025}),    Request(("new_customers",), ("customer__region",), {"metric_time__year": 2025}),]agree = 0for request in requests:    ours = con.execute(layer.sql(request)).fetchall()    theirs = as_dates(con.execute(explain_sql(mf, request)).fetchall())    same = results_match(ours, theirs, tolerance=1e-9)  # a tolerance for float rounding differences between the two engines    agree += same    print(f"{', '.join(request.metrics)} by {', '.join(request.group_by)}: {len(ours)} rows, agree: {same}")month = requests[6]  # the one request with a month grain, so its column types show MetricFlow's timestamp and the book's dateprint(f"MetricFlow's type for metric_time__month: {type(con.execute(explain_sql(mf, month)).fetchone()[0]).__name__}")print(f"the book's type for metric_time__month: {type(con.execute(layer.sql(month)).fetchone()[0]).__name__}")print(f"requests compared: {len(requests)}")print(f"requests that agree: {agree}")print(explain_sql(mf, requests[0]))  # chapter 1's question: net revenue by region in March 2026try:    explain_sql(mf, Request(("net_revenue",), ("product__category",), {"metric_time__year": 2025}))except Exception as e:    print(f"MetricFlow on net_revenue by product__category: {type(e).__name__}")    lines = [line.strip() for line in str(e).splitlines()]    cause = lines.index("* No valid join paths exist from the measure to the group-by-item.")    # MetricFlow puts each cause on one line and its explanation on the next, so the line after the cause is printed too.    print(f"one cause MetricFlow lists: {lines[cause][2:]} {lines[cause + 1]}")  # [2:] drops the bullet's "* "
出力python metricflow-agrees.py
net_revenue by order__region: 3 rows, agree: True
net_revenue, orders by metric_time__fiscal_quarter: 4 rows, agree: True
line_net_revenue, units_sold by product__category: 8 rows, agree: True
units_sold by order__customer__region: 3 rows, agree: True
refund_rate by order__country: 10 rows, agree: True
average_order_value by order__channel: 4 rows, agree: True
refunds, order_refunds by metric_time__month: 12 rows, agree: True
new_customers by customer__region: 3 rows, agree: True
MetricFlow's type for metric_time__month: datetime
the book's type for metric_time__month: date
requests compared: 8
requests that agree: 8
-- Constrain Output with WHERE
-- Select: ['__net_revenue', 'order__region']
-- Aggregate Inputs for Simple Metrics
-- Compute Metrics via Expressions
-- Order By ['order__region']
-- Write to DataTable
SELECT
  order__region
  , SUM(net_revenue) AS net_revenue
FROM (
  -- Read Elements From Semantic Model 'orders'
  -- Metric Time Dimension 'order_date'
  -- Select: ['__net_revenue', 'order__region', 'order__status', 'metric_time__month']
  SELECT
    DATE_TRUNC('month', order_date_local) AS metric_time__month
    , region AS order__region
    , status AS order__status
    , net_revenue_eur AS net_revenue
  FROM analytics.fct_orders orders_src_10000
) subq_2
WHERE (
  order__status != 'cancelled'
) AND (
  metric_time__month = '2026-03-01'
)
GROUP BY
  order__region
ORDER BY order__region
MetricFlow on net_revenue by product__category: InvalidQueryException
one cause MetricFlow lists: No valid join paths exist from the measure to the group-by-item. (fan-out join support is pending).

8 件のリクエストすべてが同じ行を返す。比較で許容する違いは型の一つだけである。MetricFlow は月を datetime、つまり午前 0 時のタイムスタンプとして返すのに対し、本書のコンパイラはそれを date にキャストする。そのため、この例では比較の前にタイムスタンプを日付に変換する。

MetricFlow の SQL はより長く、各ステップに名前を付けたコメントが付くが、本書のコンパイラと同じ地域別合計に行き着く。2025 年の商品カテゴリ別の純売上も、InvalidQueryException とともに拒否する。そのメッセージが挙げる一般的な原因の中には、結合の節で遭遇したものがある。「No valid join paths exist from the measure to the group-by-item. (fan-out join support is pending).」

MetricFlow は、本書のコンパイラよりも多くのことを YAML に求める。単純メトリクスが依拠するセマンティックモデルには、いずれも固有の時間ディメンションが必要である。次のコードはエンジンを 2 回構築する。コピーでは order_lines を、注文日を持たない分析用テーブルである analytics.fct_order_lines に向け、モデルの時間ディメンションを削除する。

metricflow-needs-a-date.py Python 3.12.15 · duckdb 2.0.0 · metricflow 0.214.0 · pydantic 2.14.3 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Show that MetricFlow won't build its engine when a fact's semantic model has no date of its own."""import shutilimport tempfilefrom pathlib import Pathimport yamlfrom lib.metricflow_bridge import enginefrom lib.semantic import SEMANTIC_DIRfrom lib.warehouse import connectcon = connect()print(f"MetricFlow with the shop's YAML: {type(engine(con)).__name__}")# A copy in which order_lines reads analytics.fct_order_lines, which has no order day, and declares no date.with tempfile.TemporaryDirectory() as tmp:    folder = Path(tmp) / "semantic"    shutil.copytree(SEMANTIC_DIR, folder)    path = folder / "order_lines.yml"    document = yaml.safe_load(path.read_text())    lines_model = document["semantic_model"]    lines_model["node_relation"] = {"schema_name": "analytics", "alias": "fct_order_lines"}    del lines_model["defaults"], lines_model["dimensions"]    path.write_text(yaml.safe_dump(document, sort_keys=False))    try:        engine(con, folder)        print("MetricFlow without a date on order_lines: built")    except Exception as e:        print(f"MetricFlow without a date on order_lines: {type(e).__name__}")        print(f"its message begins: {str(e).splitlines()[0]}")
出力python metricflow-needs-a-date.py
MetricFlow with the shop's YAML: MetricFlowEngine
MetricFlow without a date on order_lines: InvalidManifestException
its message begins: Invalid aggregation time dimension configuration

ショップの YAML からは MetricFlowEngine が構築される。コピーからは構築されない。MetricFlow は InvalidManifestException を送出し、そのメッセージは「Invalid aggregation time dimension configuration」で始まる。ショップの order_lines モデルが、各注文の現地日付を加えたビュー semantic.order_lines を読むのは、このためである。

実践ルール: 自分のレイヤーを、MetricFlow、あるいは本番でそれを提供するツールと、依拠するすべてのリクエスト形式について比較し、どちらかが変わるたびにその比較を実行すること。MetricFlow のバージョンは厳密に固定し、そのエンジンは 1 つのモジュールの背後に置くこと。Python API はどのリリースでも変わりうるからである。

一つの定義、任意のウェアハウスの方言

最終変更:版2026.11.12

本書のコンパイラのように式木へコンパイルする層は、その木を別のウェアハウス向けに書き出せる。sqlglot 30.31.0 は自らを「トランスパイラであり、バリデータではない」と称し、方言によっては翻訳できないクエリがあると警告する。また、unsupported_level が例外を送出するように設定されていない限り、既定ではベストエフォートの翻訳を行う(PyPI)。暦上の四半期ごとの各方言の返金率は、四半期と除算の2行で異なる。そのため、この例では方言ごとにその2行を出力する。あわせて、キャストしていない列から sqlglot が書き出す BigQuery の四半期も出力する。

transpile-metric-sql.py Python 3.12.15 · duckdb 2.0.0 · pyyaml 6.0.3 · sqlglot 30.31.0 合格
"""Write one compiled metric request in six warehouses' dialects, and show what transpiling doesn't check. The printed quarter and ratio lines per dialect, and the `bigquery without the cast` line, are the facts the prose states."""import sqlglotfrom sqlglot import ErrorLevelfrom lib.semantic import MetricRequest, loadrequest = MetricRequest(("refund_rate",), ("metric_time__quarter",), {"metric_time__year": 2025})compiled = load().compile(request)for dialect in ("duckdb", "snowflake", "bigquery", "databricks", "postgres", "tsql"):    sql = compiled.sql(dialect=dialect, pretty=True, unsupported_level=ErrorLevel.RAISE)    lines = [line.strip().rstrip(",") for line in sql.splitlines()]    # the quarter line is the one that truncates the date; the ratio line is the one that divides, guarded by NULLIF    print(f"{dialect} quarter: {next(line for line in lines if 'TRUNC' in line)}")    print(f"{dialect} ratio: {next(line for line in lines if 'NULLIF' in line)}")# The compiler casts the column to DATE before truncating. Without the cast, BigQuery gets TIMESTAMP_TRUNC.uncast = sqlglot.transpile("SELECT DATE_TRUNC('quarter', order_date_local)", read="duckdb", write="bigquery")[0]print(f"bigquery without the cast: {uncast}")# Transpiling translates syntax; it doesn't check that the target warehouse has the function.tsql = sqlglot.transpile("SELECT * FROM customers WHERE country ILIKE 'g%'", read="duckdb", write="tsql",                         unsupported_level=ErrorLevel.RAISE)[0]print(f"ILIKE in T-SQL: {tsql}")
出力python transpile-metric-sql.py
duckdb quarter: CAST(DATE_TRUNC('QUARTER', CAST(refunds.order_date_local AS DATE)) AS DATE) AS metric_time__quarter
duckdb ratio: order_refunds.order_refunds / NULLIF(gross_revenue.gross_revenue, 0) AS refund_rate
snowflake quarter: CAST(DATE_TRUNC('QUARTER', CAST(refunds.order_date_local AS DATE)) AS DATE) AS metric_time__quarter
snowflake ratio: order_refunds.order_refunds / NULLIF(gross_revenue.gross_revenue, 0) AS refund_rate
bigquery quarter: CAST(DATE_TRUNC(CAST(refunds.order_date_local AS DATE), QUARTER) AS DATE) AS metric_time__quarter
bigquery ratio: order_refunds.order_refunds / NULLIF(gross_revenue.gross_revenue, 0) AS refund_rate
databricks quarter: CAST(TRUNC(CAST(refunds.order_date_local AS DATE), 'QUARTER') AS DATE) AS metric_time__quarter
databricks ratio: order_refunds.order_refunds / NULLIF(gross_revenue.gross_revenue, 0) AS refund_rate
postgres quarter: CAST(DATE_TRUNC('QUARTER', CAST(refunds.order_date_local AS DATE)) AS DATE) AS metric_time__quarter
postgres ratio: CAST(order_refunds.order_refunds AS DOUBLE PRECISION) / NULLIF(gross_revenue.gross_revenue, 0) AS refund_rate
tsql quarter: CAST(DATE_TRUNC('QUARTER', CAST(refunds.order_date_local AS DATE)) AS DATE) AS metric_time__quarter
tsql ratio: CAST(order_refunds.order_refunds AS FLOAT) / NULLIF(gross_revenue.gross_revenue, 0) AS refund_rate
bigquery without the cast: SELECT TIMESTAMP_TRUNC(order_date_local, QUARTER)
ILIKE in T-SQL: SELECT * FROM customers WHERE country ILIKE 'g%'

コンパイラは、時刻列を切り詰める前に日付へキャストしており、このキャストが BigQuery の行を決める。キャストがなければ、sqlglot は SELECT TIMESTAMP_TRUNC(order_date_local, QUARTER) を書き出す。ところが BigQuery は、TIMESTAMP_TRUNC の引数を日付ではなく timestamp または datetime と定めている(Google Cloud)。キャストがあれば、BigQuery には DATE_TRUNC が渡される。これは日付と QUARTER の粒度を取る(Google Cloud)。Databricks には TRUNC が渡される。除算では、Postgres と T-SQL 向けに浮動小数点型へのキャストが加わるため、整数の比はそこでも小数のままになる。DuckDB の除算演算子は、もともと浮動小数点の除算である(DuckDB)。

これらの行からは、2つの限界が読み取れる。第一に、同じキャストが T-SQL に影響する。T-SQL の四半期の行は DATE_TRUNC となるが、Microsoft は T-SQL の関数を、アンダースコアのない DATETRUNC と定めている(Microsoft)。ある方言のための修正が別の方言を壊したのかもしれない。この例ではすべての方言に unsupported_level=ErrorLevel.RAISE を設定しているにもかかわらず、sqlglot は何も送出しなかった。第二に、最後の行の ILIKE は、unsupported_level=ErrorLevel.RAISE を設定しても T-SQL にそのまま渡される。T-SQL のパターンマッチは LIKE であり、ILIKE はない(Microsoft)。ここでは BigQuery も SQL Server も実行できなかった。トランスパイルできたクエリであっても、対象のウェアハウスで実行して確かめる必要がある。

実践ルール: 定義は一つに保ってトランスパイルする。ただし、各方言の SQL は、そのウェアハウス上で既知の答えと照合して実行するまでは未検証として扱う。コンパイラでは日付と除算を明示的にキャストし、翻訳時の推測を減らす。

本番環境で起こる問題

最終変更:版2026.11.13

この店のセマンティックレイヤーは、店のゴールデンクエスチョンには答えられる。しかし実際のウェアハウスでは、リスクは宣言、日付、エンジンのそれぞれにあり、どのリスクにも注意すべき症状がある。

誤ったエンティティ型は、ファンアウト保護を無効にする。 外部キーを主キーとして宣言すると、レイヤーは複数の行を1行であるかのように結合し、その結合を通るすべての合計が水増しされる。構文解析ではこれを検出できない。check()が行っているように、すべての主エンティティについてデータ内の重複を数える。これを CI で、またロードのたびに実行する。

独自の日付を持たないファクトは、メトリクスを担えない。 MetricFlow は、各シンプルメトリクスと同じセマンティックモデルに時間ディメンションがあることを求める。0.214.0では、時間ディメンションがないとエンジンの構築を拒否する。これは、MetricFlow の節がInvalidManifestExceptionで示すとおりである。この店の注文明細には日付がなく、このレイヤーを書いている途中でそれに気づいた。そのため、ウェアハウスは各注文のローカル日付を持つsemantic.order_linesを追加している。マートのすべてのファクトテーブルに、業務日付を持たせる。

1つのメトリクスに2つの定義があると、次第にずれていく。 レイヤーで定義したメトリクスを、ダッシュボード、ノートブック、エージェントのプロンプトで再度定義すると、どちらか一方を最初に変更した時点で両者は食い違う。第1章のメトリクスが YAML から定義を読み取るのは、このためである。各メトリクスの列をレイヤーの外で検索し、YAML を変更するたびにゴールデンクエスチョンを実行する。

フィルターはテンプレートであり、テンプレートはコードである。 メトリクスのfilterは Jinja テンプレートであり、MetricFlow の変更履歴には、セキュリティ上の問題を修正するためにそのレンダリングをサンドボックス化したことが記録されている(dbt Labs)。モデルやユーザーが書いたフィルター文字列を、レイヤーに渡してはならない。lib/semantic.pyのMetricRequestのように構造化されたフィルターを送り、テンプレートは YAML を保守する人のために残す。第9章では、この箇所に行フィルターを組み込む。

エンジンの API は変わる。 MetricFlow の Python エンジンは内部向けであり、バージョンは 0.x である。リリースによって引数名が変わったり、SQL の形が変わったりすることがある。呼び出しはすべて1つのモジュールにまとめ、バージョンを厳密に固定し、アップグレードで数値が変わったかどうかは、自前のコンパイラーまたはゴールデン結果との比較で確認する。

フォーマットも変わる。 dbt v1.12 以降の dbt の仕様では、エンティティとディメンションが columns の下に移り、メジャーはシンプルメトリクスに置き換えられる(dbt Labs)。かつて Open Semantic Interchange と呼ばれた Apache Ossie も別のフォーマットであり(Apache Ossie)、その変更履歴が記録するとおり、MetricFlow にはそのためのコンバーターが含まれている。フォーマットは1つに決めてバージョン管理下に置き、変換は手作業ではなく、テスト済みのツールで行う。

実践ルール: セマンティックレイヤーはコードと同じようにテストする。エンティティの一意性をデータに対して確認し、すべてのメトリクスの SQL を CI で実行し、変更のたびに MetricFlow およびゴールデンクエスチョンと比較し、レイヤーを保守する人以外からは構造化されたリクエストだけを受け付ける。

この章で下した決定

最終変更:版2026.11.13
  • ショップの指標は一か所にまとめる。 指標は examples/data/semantic/*.yml に置き、MetricFlow のスタンドアロン YAML で記述する。内訳は、五つのセマンティックモデル、十個の指標、一つのタイムスパインである。第 1 章の net_revenue は、定義をここから読み込む。
  • 単純な指標はメジャーを使わない。 各指標は、所属するセマンティックモデル、集計方法、式を指定する。これは dbt の仕様が採る方向であり、MetricFlow 0.214.0 はこの形式を読み込める。
  • 本書は独自のコードでコンパイルする。 そのコードは lib/semantic.py であり、sqlglot の式を構築する。結合は多対一に限り、比率や複数指標のリクエストでは各入力をそれぞれ別に集計する。ファンアウトが起きる場合は、理由を示して拒否する。
  • リクエストが運ぶのは名前と値であり、SQL は運ばない。 フィルタの値は、式ツリーの中でリテラルになる。
  • 会計カレンダーは、タイムスパインのカスタム粒度とする。 粒度は fiscal_year と fiscal_quarter であり、各値が一つの期間を指すようにラベルを付ける。
  • ウェアハウスに semantic スキーマを加える。 スキーマは三つのビューからなり、すべてのファクトが固有の日付を持ち、すべての会計四半期に名前が付く。raw スキーマと analytics スキーマ、および記録済みのすべてのプロンプトは変更しない。
  • dbt を使わず、MetricFlow だけで定義を検証する。 検証は一つのモジュールを通して行い、本章で比較するすべてのリクエストで、本書のコンパイラと結果が一致する。metricflow パッケージは Apache 2.0 で提供され、dbt に依存せずオフラインで動作する。本番での通常の経路は dbt-metricflow である。
  • 一つの定義をウェアハウスごとにトランスパイルする。 時間列は、切り捨ての前に日付型へキャストする。トランスパイルした SQL は、そのウェアハウスで実行するまでは未検証として扱う。
  • 率は合計の比として定義する。 分子と分母はそれぞれ、独自のフィルタと時間ディメンションで別々に集計する。返品率は、その期間の注文に対する返品額を、それらの注文の総売上で割ったものである。総売上は返品額と同様に税を含む。本書の用語集と検証済みクエリも、同じ定義を用いる。
  • 定義は構文解析だけでなく、データに照らして検証する。 すべての式を実行し、すべての主エンティティが一意であることを確認する。これにより、誤って宣言されたキーが合計を膨らませる前に検出できる。

この版における本章

第2026.11.15版2026年11月19日時点で例が通過この章の8 例件のうち8件が合格

英語版の書籍(版2026.11.15)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全11章中の第5章: セマンティックレイヤーで指標を一度だけ定義する

  1. Describe each table as a semantic model
  2. Compile a metric request to SQL
  3. Join through entities so sums can't fan out
  4. 単純なメトリクスから比率メトリクスと派生メトリクスを作る
  5. 会計カレンダーをタイムスパインに置く
  6. 定義を MetricFlow で検証する
  7. 一つの定義、任意のウェアハウスの方言
  8. 本番環境で起こる問題
  9. この章で下した決定

ページの先頭に戻るすべての章