Metrics
Define calculations and key performance indicators in your semantic layer
1. Introduction to Metrics
Metrics are calculations based on measures or dimensions within your semantic models. They represent key business performance indicators (KPIs) and other frequently used calculations, encapsulating business logic centrally.
Here’s the basic structure for defining a metric:
2. Defining Basic Metrics
At their core, metrics combine a name, a calculation expression (expr
), and a description.
Required Fields
name
: A unique identifier for the metric within the model. Use clear, descriptive names.expr
: A SQL-like expression that defines the calculation. This expression forms the basis of the metric’s value.description
: A clear explanation of what the metric represents in business terms. This is mandatory and crucial for understanding.
Writing the expr
The expr
field is where you define the metric’s calculation using SQL syntax compatible with your data warehouse.
- Referencing Fields: You can directly reference dimensions and measures defined within the same model (e.g.,
amount
,user_id
). - Aggregations: Use standard SQL aggregation functions:
SUM
,AVG
,COUNT
,COUNT DISTINCT
,MIN
,MAX
, etc. - Operators: Arithmetic (
+
,-
,*
,/
), logical (AND
,OR
,NOT
), comparison (=
,>
,<
, etc.) are supported. - Functions: Most standard SQL functions like
CASE
,COALESCE
,NULLIF
, date functions, string functions, etc., can be used.
When referencing fields within the same model in the expr
, you typically don’t need a table prefix (e.g., SUM(amount)
is usually sufficient if amount
is a measure in the current model). However, using prefixes (e.g., SUM(orders.amount)
) can enhance clarity, especially in complex models. See Best Practices for more on prefixes when using related models.
Example: Basic Metric
3. Advanced Metric Types
Beyond basic calculations, you can create more dynamic and interconnected metrics.
Parameterized Metrics
Create flexible metrics that accept user inputs at query time. Define parameters using the args
field and reference them in the expr
using double curly braces {{parameter_name}}
.
args
: A list defining each parameter.name
: The parameter name used in theexpr
(e.g.,{{days}}
) (required).type
: Data type (string
,integer
,number
,date
,boolean
) (required).description
: Explanation for the user (required).default
(Optional): A default value if the user doesn’t provide one.
Example: Parameterized Metric
Cross-Model Metrics
Reference fields (dimensions or measures) from related models using dot notation (related_model_name.field_name
). This requires an entity
relationship to be defined between the models involved.
Example: Cross-Model Metric
Using cross-model references requires careful consideration of joins when querying. See “Handling Joins and Related Models” below.
4. Best Practices & Considerations
Follow these guidelines to create robust, understandable, and maintainable metrics.
General Best Practices
Business Focus
Define metrics that represent meaningful business KPIs, translating raw data into actionable insights.
Clear Naming & Descriptions
Use consistent, descriptive names and provide mandatory, clear descriptions explaining the calculation and business purpose.
Leverage Existing Components
Build metrics by referencing existing measures and dimensions within the model rather than duplicating complex logic.
Document Dependencies
If a metric relies on parameters or data from related models (via entities), clearly state these requirements in its description
.
Expression Best Practices
- Type Consistency: Ensure metric expressions resolve to appropriate data types (usually numeric) suitable for aggregation or further calculations.
- Use Table Prefixes for Related Models: Always use table-qualified names (e.g.,
customer.id
,orders.amount
) in yourexpr
when referencing fields from related models (via entities) to prevent ambiguity. Prefixes are optional but recommended for clarity even for fields in the primary model. - SQL Conventions:
- Wrap complex expressions or calculations in parentheses
()
to ensure correct operator precedence. - Handle potential division-by-zero errors using
NULLIF(denominator, 0)
. Example:SUM(profit) / NULLIF(SUM(revenue), 0)
. - Be mindful of nulls. Use
COALESCE
or other relevant SQL functions to handle them appropriately within calculations, especially when dealing with outer joins.
- Wrap complex expressions or calculations in parentheses
- Avoid Circular References: Do not define metrics that refer back to themselves directly or indirectly.
Good Expression Example (Parameterized):
Parameter Best Practices
- Explicit Typing: Always define the
type
for each parameter (string
,integer
,number
,date
,boolean
). This enables validation and correct query generation. - Clear Documentation: Provide a meaningful
description
for each parameter. - Placeholders: Reference parameters in the
expr
using double curly braces:{{parameter_name}}
. - Default Values: Provide
default
values for optional parameters to simplify usage. - Validation Notes:
string
: Will be automatically quoted if needed during query generation.number
/integer
: Must be valid numeric values.date
: Should ideally be provided in ISO format (YYYY-MM-DD
).boolean
: Should betrue
/false
(or potentially1
/0
depending on backend).
Parameter Definition Pattern to Avoid:
Handling Joins and Related Models
- Primary Association: Each metric belongs primarily to the model where it’s defined.
- Explicit Joins Required in Query: If a metric’s
expr
references fields from a related model (e.g.,customer.id
), the query using that metric must explicitly include the necessary join to that related model via its definedentity
. - No Automatic Joins: The semantic layer does not automatically infer or add joins based solely on the metric’s
expr
. It validates that joins used in a query correspond to definedentities
. - Robustness with Joins: When dealing with related models (especially via outer joins), consider using
CASE
statements or checking for nulls on fields from those models to make the metric resilient to missing data.
5. Comprehensive Example
Here’s an example within an orders
model context, incorporating various metric types and practices:
6. Next Steps
With your metrics defined, consider:
- Defining Filters for reusable query conditions.
- Establishing Relationships (Entities) to link different models together, enabling cross-model metrics.
- Reviewing Complete Examples of semantic model definitions.
By following these structures and practices, your metrics will be powerful, understandable, and easier to manage within your semantic layer.