Table of Contents

Add an object to a Metric View

This how-to demonstrates how to add a new Metric View dimension (field) to a loaded Metric View. Similar patterns apply to all Metric View collections.

Deserialize Metric View for these code samples

This how-to uses a sample e-commerce Metric View representing sales data with three dimension tables (product, customer, date) joined to a fact table (orders). Run the snippet below first, if you'd like to follow along with the code in the rest of this how-to

SemanticBridge.MetricView.Deserialize("""
    version: 0.1
    source: sales.fact.orders
    joins:
      - name: product
        source: sales.dim.product
        on: source.product_id = product.product_id
      - name: customer
        source: sales.dim.customer
        on: source.customer_id = customer.customer_id
      - name: date
        source: sales.dim.date
        on: source.order_date = date.date_key
    dimensions:
      - name: product_name
        expr: product.product_name
      - name: product_category
        expr: product.category
      - name: customer_segment
        expr: customer.segment
      - name: order_date
        expr: date.full_date
      - name: order_year
        expr: date.year
      - name: order_month
        expr: date.month_name
    measures:
      - name: total_revenue
        expr: SUM(revenue)
      - name: order_count
        expr: COUNT(order_id)
      - name: avg_order_value
        expr: AVG(revenue)
      - name: unique_customers
        expr: COUNT(DISTINCT customer_id)
    """);

Create a new Metric View Dimension object

Use the Metric View Dimension constructor to create a new Metric View dimension:

using MetricView = TabularEditor.SemanticBridge.Platforms.Databricks.MetricView;

var newDimension = new MetricView.Dimension
{
    Name = "customer_city",
    Expr = "customer.city"
};

Add to the Metric View

The Metric View Dimensions property is an IList<Dimension>, so you can use Add():

using MetricView = TabularEditor.SemanticBridge.Platforms.Databricks.MetricView;

var sb = new System.Text.StringBuilder();
sb.AppendLine($"Dimensions before adding: {SemanticBridge.MetricView.Model.Dimensions.Count}");

var newDimension = new MetricView.Dimension
{
    Name = "customer_city",
    Expr = "customer.city"
};

SemanticBridge.MetricView.Model.Dimensions.Add(newDimension);

sb.AppendLine($"Dimensions after adding: {SemanticBridge.MetricView.Model.Dimensions.Count}");
Output(sb.ToString());

Output

Dimensions before adding: 8
Dimensions after adding: 9

See also