claude-skills/

Anthropic公式スキル・プラグインの日本語ディレクトリ

last sync 22h ago
スキルOfficialdatabase

📊databricks-metric-views

プラグイン
databricks

説明

Unity Catalog メトリックビュー: YAML 形式でガバナンスされたビジネスメトリクスを定義・作成・クエリ・管理します。 次のような場合に使用: 標準化された KPI、収益メトリクス、注文分析、またはチームやツールを横断して一貫した定義が必要な再利用可能なビジネスメトリクスを構築する場合。

原文を表示

Unity Catalog metric views: define, create, query, and manage governed business metrics in YAML. Use when building standardized KPIs, revenue metrics, order analytics, or any reusable business metrics that need consistent definitions across teams and tools.

ユースケース

  • 標準化されたKPIを構築するとき
  • 収益メトリクスを定義するとき
  • 注文分析を実施するとき
  • チーム横断でメトリクスを統一するとき

本文(日本語訳)

Unity Catalog Metric Views

メジャー定義とディメンショングループを分離し、柔軟なクエリを実現する再利用可能でガバナンスされたビジネスメトリクスをYAMLで定義します。

次のような場合に使用

次のような場合に使用:

  • 標準化されたビジネスメトリクス(売上、注文数、コンバージョン率など)を定義する場合
  • ダッシュボード、Genie、SQLクエリ間で共有されるKPIレイヤーを構築する場合
  • 複雑な集計(比率、DISTINCT COUNT、フィルター付きメジャーなど)を含むメトリクスを作成する場合
  • ウィンドウメジャー(移動平均、累計、前期比、YTD)を定義する場合
  • メトリクス定義にJOINを含むスタースキーマまたはスノーフレークスキーマをモデリングする場合
  • 事前集計されたメトリクス集約のマテリアライゼーションを有効化する場合

前提条件

  • Databricks Runtime 17.2以降(YAMLバージョン1.1の場合)
  • CAN USE 権限を持つSQLウェアハウス
  • ソーステーブルへの SELECT 権限、ターゲットスキーマへの CREATE TABLE および USE SCHEMA 権限

クイックスタート

ソーステーブルスキーマの確認

Metric Viewを作成する前に、ソーステーブルを確認してください。 デフォルトとして discover-schema を使用することを推奨します。 1回の呼び出しで、カラム名・型・サンプル行・NULL数・行数が返されます。 スキーマ名しかわからない場合は、先に query "SHOW TABLES IN ..." でテーブル一覧を取得してください。

databricks experimental aitools tools discover-schema catalog.schema.orders catalog.schema.customers

ディメンションとメジャーについては、サンプリングを超えた分布の調査も行ってください。 具体的には、ディメンション候補のカーディナリティ、メジャーの最小値・最大値・パーセンタイル、カテゴリ値の上位件数などです。 集計SQLは databricks experimental aitools tools query --warehouse <WH> "..." で実行できます。 どちらのコマンドもデフォルトウェアハウスを自動選択します。 上書きする場合は DATABRICKS_WAREHOUSE_ID を設定するか、--warehouse <ID> を渡してください。

Metric Viewの作成

CREATE OR REPLACE VIEW catalog.schema.orders_metrics
WITH METRICS
LANGUAGE YAML
AS $$
  version: 1.1
  source: catalog.schema.orders
  comment: "Orders KPIs for sales analysis"
  filter: order_date > '2020-01-01'
  dimensions:
    - name: Order Month
      expr: DATE_TRUNC('MONTH', order_date)
      comment: "Month of order"
    - name: Order Status
      expr: CASE
        WHEN status = 'O' THEN 'Open'
        WHEN status = 'P' THEN 'Processing'
        WHEN status = 'F' THEN 'Fulfilled'
        END
      comment: "Human-readable order status"
  measures:
    - name: Order Count
      expr: COUNT(1)
    - name: Total Revenue
      expr: SUM(total_price)
      comment: "Sum of total price"
    - name: Revenue per Customer
      expr: SUM(total_price) / COUNT(DISTINCT customer_id)
      comment: "Average revenue per unique customer"
$$

Metric Viewのクエリ

すべてのメジャーは MEASURE() 関数を使用する必要があります。SELECT * はサポートされていません。

SELECT
  `Order Month`,
  `Order Status`,
  MEASURE(`Total Revenue`) AS total_revenue,
  MEASURE(`Order Count`) AS order_count
FROM catalog.schema.orders_metrics
WHERE extract(year FROM `Order Month`) = 2024
GROUP BY ALL
ORDER BY ALL

リファレンスファイル

トピック ファイル 説明
YAML構文 references/yaml-reference.md YAMLの完全仕様: ディメンション、メジャー、JOIN、マテリアライゼーション
パターンと例 references/patterns.md 代表的なパターン: スタースキーマ、スノーフレーク、フィルター付きメジャー、ウィンドウメジャー、比率

SQL操作

Metric Viewの作成

CREATE OR REPLACE VIEW catalog.schema.orders_metrics
WITH METRICS
LANGUAGE YAML
AS $$
  version: 1.1
  comment: "Orders KPIs for sales analysis"
  source: catalog.schema.orders
  filter: order_date > '2020-01-01'
  dimensions:
    - name: Order Month
      expr: DATE_TRUNC('MONTH', order_date)
      comment: "Month of order"
    - name: Order Status
      expr: status
  measures:
    - name: Order Count
      expr: COUNT(1)
    - name: Total Revenue
      expr: SUM(total_price)
      comment: "Sum of total price"
$$;

Metric Viewのクエリ

SELECT
  `Order Month`,
  MEASURE(`Total Revenue`) AS total_revenue,
  MEASURE(`Order Count`) AS order_count
FROM catalog.schema.orders_metrics
WHERE extract(year FROM `Order Month`) = 2024
GROUP BY ALL
ORDER BY ALL
LIMIT 100;

Metric Viewの詳細確認

DESCRIBE TABLE EXTENDED catalog.schema.orders_metrics;

-- またはYAML定義を取得
SHOW CREATE TABLE catalog.schema.orders_metrics;

アクセス権限の付与

GRANT SELECT ON VIEW catalog.schema.orders_metrics TO `data-consumers`;

Metric Viewの削除

DROP VIEW IF EXISTS catalog.schema.orders_metrics;

CLI実行

# CLI経由でSQLを実行
databricks experimental aitools tools query --warehouse WAREHOUSE_ID "
CREATE OR REPLACE VIEW catalog.schema.orders_metrics
WITH METRICS
LANGUAGE YAML
AS \$\$
  version: 1.1
  source: catalog.schema.orders
  dimensions:
    - name: Order Month
      expr: DATE_TRUNC('MONTH', order_date)
  measures:
    - name: Total Revenue
      expr: SUM(total_price)
\$\$
"

ヒアドキュメントのエスケープを避けるには: 上記の \$\$ によるトークンクォートは不安定です(bashの変数展開、sed、JSONエンコーディングと干渉します)。 長いDDLの場合は、SQLをJSON文字列として渡せるStatement Execution APIの使用を推奨します:

databricks api post /api/2.0/sql/statements --json '{
  "warehouse_id": "WAREHOUSE_ID",
  "statement": "CREATE OR REPLACE VIEW catalog.schema.orders_metrics WITH METRICS LANGUAGE YAML AS $$\nversion: 1.1\nsource: catalog.schema.orders\ndimensions:\n  - name: Order Month\n    expr: DATE_TRUNC(MONTH, order_date)\nmeasures:\n  - name: Total Revenue\n    expr: SUM(total_price)\n$$"
}'

JSONエスケープされた文字列は、シェルのヒアドキュメントよりもプログラムでのテンプレート生成が容易です。

既存のViewをMetric Viewに変換する

通常のViewをMetric Viewに移行するには、その SELECT のソースをMetric Viewの source として扱い、GROUP BY カラムを dimensions に、集計式を measures に昇格させます。 新しいMetric Viewは元のViewを置き換えるのではなく、ガバナンスされたメトリクスレイヤーとして並列に配置されます。

-- 既存の通常View(そのまま残すか、後で削除)
-- CREATE VIEW catalog.schema.orders_summary AS
-- SELECT DATE_TRUNC('MONTH', order_date) AS month,
--        SUM(total_price) AS revenue,
--        COUNT(*) AS order_count
-- FROM catalog.schema.orders
-- GROUP BY 1;

-- 相当するMetric View(新しいアーティファクト、ガバナンス済み)
CREATE OR REPLACE VIEW catalog.schema.orders_metrics
WITH METRICS
LANGUAGE YAML
AS $$
  version: 1.1
  source: catalog.schema.orders
  dimensions:
    - name: Order Month
      expr: DATE_TRUNC('MONTH', order_date)
  measures:
    - name: Revenue
      expr: SUM(total_price)
    - name: Order Count
      expr: COUNT(1)
$$

同等性を確認したら(SELECT ... FROM <orders_metrics> が元のViewと同じ数値を返すことを確認)、ダウンストリームのコンシューマを更新し、元のViewを削除してください。

YAMLスペッククイックリファレンス

version: 1.1                    # 必須: DBR 17.2+ の場合は "1.1"
source: catalog.schema.table    # 必須: ソーステーブル/View
comment: "Description"          # 任意: Metric Viewの説明
filter: column > value          # 任意: グローバルWHEREフィルター

dimensions:                     # 必須: 1つ以上
  - name: Display Name          # クエリではバッククォートで囲む
    expr: sql_expression        # カラム参照またはSQL変換式
    comment: "Description"      # 任意 (v1.1以降)

measures:                       # 必須: 1つ以上
  - name: Display Name          # MEASURE(`name`) でクエリ
    expr: AGG_FUNC(column)      # 集計式であること
    comment: "Description"      # 任意 (v1.1以降)

joins:                          # 任意: スター/スノーフレークスキーマ
  - name: dim_table
    source: catalog.schema.dim_table
    on: source.fk = dim_table.pk

materialization:                # 任意 (実験的機能)
  schedule: every 6 hours
  mode: relaxed

主要コンセプト

ディメンション vs メジャー

ディメンション メジャー
目的 データの分類とグループ化 数値の集計
Region、Date、Status SUM(revenue)、COUNT(orders)
クエリ内での扱い SELECTおよびGROUP BYで使用 MEASURE() でラップ
SQL式 任意のSQL式 集計関数を使用すること

標準Viewと比べたMetric Viewの利点

機能 標準View Metric View
集計の固定化 作成時に固定 不要 — クエリ時に柔軟に指定可
比率の安全な再集計 不可 可能
スター/スノーフレークスキーマのJOIN 手動 YAMLで宣言的に定義
マテリアライゼーション 別途マテリアライズドViewが必要 組み込み済み
AI/BI Genieとの統合 限定的 ネイティブ対応

よくある問題

問題 解決策
SELECT * が非対応 ディメンションを明示的に列挙し、メジャーは MEASURE() でラップすること
"Cannot resolve column" エラー スペースを含むディメンション/メジャー名はバッククォートで囲む必要がある
クエリ時のJOINが失敗する JOINはSELECTクエリではなく、YAMLの定義内に記述する必要がある
MEASURE() が必須 すべてのメジャー参照は MEASURE(\name`)` でラップすること
DBRバージョンエラー YAML v1.1にはRuntime 17.2以降、v0.1には16.4以降が必要
マテリアライゼーションが動作しない サーバーレスコンピュートの有効化が必要。現時点では実験的機能

インテグレーション

Metric Viewは以下とネイティブに連携します:

  • AI/BI Dashboards — ビジュアライゼーションのデータセットとして使用
  • AI/BI Genie — メトリクスへの自然言語クエリ
  • Alerts — メジャーへのしきい値ベースのアラート設定
  • SQL Editor — MEASURE() を使った直接SQLクエリ
  • Catalog Explorer UI — ビジュアルによる作成とブラウジング

リソース

原文(English)を表示

Unity Catalog Metric Views

Define reusable, governed business metrics in YAML that separate measure definitions from dimension groupings for flexible querying.

When to Use

Use this skill when:

  • Defining standardized business metrics (revenue, order counts, conversion rates)
  • Building KPI layers shared across dashboards, Genie, and SQL queries
  • Creating metrics with complex aggregations (ratios, distinct counts, filtered measures)
  • Defining window measures (moving averages, running totals, period-over-period, YTD)
  • Modeling star or snowflake schemas with joins in metric definitions
  • Enabling materialization for pre-computed metric aggregations

Prerequisites

  • Databricks Runtime 17.2+ (for YAML version 1.1)
  • SQL warehouse with CAN USE permissions
  • SELECT on source tables, CREATE TABLE + USE SCHEMA in the target schema

Quick Start

Inspect Source Table Schema

Before authoring a metric view, inspect the source tables. Use discover-schema as the default — one call returns columns, types, sample rows, null counts, and row count. If you only know the schema, list tables first with query "SHOW TABLES IN ...".

databricks experimental aitools tools discover-schema catalog.schema.orders catalog.schema.customers

For dimensions and measures, probe distribution beyond sampling — cardinality of candidate dimensions, min/max/percentiles for measures, top categorical values. Write aggregate SQL through databricks experimental aitools tools query --warehouse <WH> "...". Both commands auto-pick the default warehouse; set DATABRICKS_WAREHOUSE_ID or pass --warehouse <ID> to override.

Create a Metric View

CREATE OR REPLACE VIEW catalog.schema.orders_metrics
WITH METRICS
LANGUAGE YAML
AS $$
  version: 1.1
  source: catalog.schema.orders
  comment: "Orders KPIs for sales analysis"
  filter: order_date > '2020-01-01'
  dimensions:
    - name: Order Month
      expr: DATE_TRUNC('MONTH', order_date)
      comment: "Month of order"
    - name: Order Status
      expr: CASE
        WHEN status = 'O' THEN 'Open'
        WHEN status = 'P' THEN 'Processing'
        WHEN status = 'F' THEN 'Fulfilled'
        END
      comment: "Human-readable order status"
  measures:
    - name: Order Count
      expr: COUNT(1)
    - name: Total Revenue
      expr: SUM(total_price)
      comment: "Sum of total price"
    - name: Revenue per Customer
      expr: SUM(total_price) / COUNT(DISTINCT customer_id)
      comment: "Average revenue per unique customer"
$$

Query a Metric View

All measures must use the MEASURE() function. SELECT * is NOT supported.

SELECT
  `Order Month`,
  `Order Status`,
  MEASURE(`Total Revenue`) AS total_revenue,
  MEASURE(`Order Count`) AS order_count
FROM catalog.schema.orders_metrics
WHERE extract(year FROM `Order Month`) = 2024
GROUP BY ALL
ORDER BY ALL

Reference Files

Topic File Description
YAML Syntax references/yaml-reference.md Complete YAML spec: dimensions, measures, joins, materialization
Patterns & Examples references/patterns.md Common patterns: star schema, snowflake, filtered measures, window measures, ratios

SQL Operations

Create Metric View

CREATE OR REPLACE VIEW catalog.schema.orders_metrics
WITH METRICS
LANGUAGE YAML
AS $$
  version: 1.1
  comment: "Orders KPIs for sales analysis"
  source: catalog.schema.orders
  filter: order_date > '2020-01-01'
  dimensions:
    - name: Order Month
      expr: DATE_TRUNC('MONTH', order_date)
      comment: "Month of order"
    - name: Order Status
      expr: status
  measures:
    - name: Order Count
      expr: COUNT(1)
    - name: Total Revenue
      expr: SUM(total_price)
      comment: "Sum of total price"
$$;

Query Metric View

SELECT
  `Order Month`,
  MEASURE(`Total Revenue`) AS total_revenue,
  MEASURE(`Order Count`) AS order_count
FROM catalog.schema.orders_metrics
WHERE extract(year FROM `Order Month`) = 2024
GROUP BY ALL
ORDER BY ALL
LIMIT 100;

Describe Metric View

DESCRIBE TABLE EXTENDED catalog.schema.orders_metrics;

-- Or get YAML definition
SHOW CREATE TABLE catalog.schema.orders_metrics;

Grant Access

GRANT SELECT ON VIEW catalog.schema.orders_metrics TO `data-consumers`;

Drop Metric View

DROP VIEW IF EXISTS catalog.schema.orders_metrics;

CLI Execution

# Execute SQL via CLI
databricks experimental aitools tools query --warehouse WAREHOUSE_ID "
CREATE OR REPLACE VIEW catalog.schema.orders_metrics
WITH METRICS
LANGUAGE YAML
AS \$\$
  version: 1.1
  source: catalog.schema.orders
  dimensions:
    - name: Order Month
      expr: DATE_TRUNC('MONTH', order_date)
  measures:
    - name: Total Revenue
      expr: SUM(total_price)
\$\$
"

Avoiding heredoc escaping: the \$\$ token-quoting above is fragile (it interacts with bash variable expansion, sed, and JSON encoding). For long DDL, prefer the Statement Execution API which takes the SQL as a JSON string:

databricks api post /api/2.0/sql/statements --json '{
  "warehouse_id": "WAREHOUSE_ID",
  "statement": "CREATE OR REPLACE VIEW catalog.schema.orders_metrics WITH METRICS LANGUAGE YAML AS $$\nversion: 1.1\nsource: catalog.schema.orders\ndimensions:\n  - name: Order Month\n    expr: DATE_TRUNC(MONTH, order_date)\nmeasures:\n  - name: Total Revenue\n    expr: SUM(total_price)\n$$"
}'

JSON-escaped strings are easier to template programmatically than shell heredocs.

Convert an Existing View to a Metric View

To migrate a regular view to a metric view, treat its SELECT source as the metric view's source, then promote GROUP BY columns to dimensions and aggregations to measures. The new metric view does not replace the original — it sits alongside it as a governed metric layer.

-- Existing regular view (keep as-is or drop later)
-- CREATE VIEW catalog.schema.orders_summary AS
-- SELECT DATE_TRUNC('MONTH', order_date) AS month,
--        SUM(total_price) AS revenue,
--        COUNT(*) AS order_count
-- FROM catalog.schema.orders
-- GROUP BY 1;

-- Equivalent metric view (new artifact, governed)
CREATE OR REPLACE VIEW catalog.schema.orders_metrics
WITH METRICS
LANGUAGE YAML
AS $$
  version: 1.1
  source: catalog.schema.orders
  dimensions:
    - name: Order Month
      expr: DATE_TRUNC('MONTH', order_date)
  measures:
    - name: Revenue
      expr: SUM(total_price)
    - name: Order Count
      expr: COUNT(1)
$$

After verifying parity (SELECT ... FROM <orders_metrics> returns the same numbers as the original view), update downstream consumers and drop the original view.

YAML Spec Quick Reference

version: 1.1                    # Required: "1.1" for DBR 17.2+
source: catalog.schema.table    # Required: source table/view
comment: "Description"          # Optional: metric view description
filter: column > value          # Optional: global WHERE filter

dimensions:                     # Required: at least one
  - name: Display Name          # Backtick-quoted in queries
    expr: sql_expression        # Column ref or SQL transformation
    comment: "Description"      # Optional (v1.1+)

measures:                       # Required: at least one
  - name: Display Name          # Queried via MEASURE(`name`)
    expr: AGG_FUNC(column)      # Must be an aggregate expression
    comment: "Description"      # Optional (v1.1+)

joins:                          # Optional: star/snowflake schema
  - name: dim_table
    source: catalog.schema.dim_table
    on: source.fk = dim_table.pk

materialization:                # Optional (experimental)
  schedule: every 6 hours
  mode: relaxed

Key Concepts

Dimensions vs Measures

Dimensions Measures
Purpose Categorize and group data Aggregate numeric values
Examples Region, Date, Status SUM(revenue), COUNT(orders)
In queries Used in SELECT and GROUP BY Wrapped in MEASURE()
SQL expressions Any SQL expression Must use aggregate functions

Why Metric Views vs Standard Views?

Feature Standard Views Metric Views
Aggregation locked at creation Yes No - flexible at query time
Safe re-aggregation of ratios No Yes
Star/snowflake schema joins Manual Declarative in YAML
Materialization Separate MV needed Built-in
AI/BI Genie integration Limited Native

Common Issues

Issue Solution
SELECT * not supported Must explicitly list dimensions and use MEASURE() for measures
"Cannot resolve column" Dimension/measure names with spaces need backtick quoting
JOIN at query time fails Joins must be in the YAML definition, not in the SELECT query
MEASURE() required All measure references must be wrapped: MEASURE(\name`)`
DBR version error Requires Runtime 17.2+ for YAML v1.1, or 16.4+ for v0.1
Materialization not working Requires serverless compute enabled; currently experimental

Integrations

Metric views work natively with:

  • AI/BI Dashboards - Use as datasets for visualizations
  • AI/BI Genie - Natural language querying of metrics
  • Alerts - Set threshold-based alerts on measures
  • SQL Editor - Direct SQL querying with MEASURE()
  • Catalog Explorer UI - Visual creation and browsing

Resources

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。