{"id":9108,"library":"metricflow","title":"MetricFlow","description":"MetricFlow is a Python library (version 0.209.0) developed by dbt Labs that serves as the engine for defining, querying, and serving metrics from dbt projects. It translates high-level metric definitions into reusable SQL and executes them against various data platforms. While it powers the dbt Semantic Layer, direct programmatic API usage is primarily for advanced scenarios like custom metric servers or programmatic SQL generation, rather than typical application-level querying. Releases typically align with dbt Core release cycles or critical updates for MetricFlow's standalone capabilities.","status":"active","version":"0.209.0","language":"en","source_language":"en","source_url":"https://github.com/dbt-labs/metricflow","tags":["dbt","semantic-layer","metrics","sql-generation","data-modeling"],"install":[{"cmd":"pip install metricflow","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Core dependency for shared dbt utilities; version conflicts are common.","package":"dbt-common","optional":false},{"reason":"Used for parsing dbt project structures and manifest data; version conflicts are common.","package":"dbt-extractor","optional":false},{"reason":"Required for parsing semantic model definitions in YAML.","package":"pyyaml","optional":false},{"reason":"Specific database adapters (e.g., dbt-postgres, dbt-snowflake) are required for actual query execution.","package":"dbt-adapters","optional":true}],"imports":[{"note":"The core class for interacting with the MetricFlow engine programmatically.","symbol":"MetricFlowEngine","correct":"from metricflow.engine.metricflow_engine import MetricFlowEngine"},{"note":"Used to configure the MetricFlow engine, including dbt project path and profiles.","symbol":"MetricFlowConfig","correct":"from metricflow.config.metricflow_config import MetricFlowConfig"},{"note":"Defines the metrics and dimensions to be queried.","symbol":"MetricFlowQuerySpec","correct":"from metricflow.specs.query_specs import MetricFlowQuerySpec"}],"quickstart":{"code":"import os\nimport tempfile\nfrom pathlib import Path\nimport shutil\n\nfrom metricflow.engine.metricflow_engine import MetricFlowEngine\nfrom metricflow.config.metricflow_config import MetricFlowConfig\nfrom metricflow.connection.null_metricflow_connection import NullMetricFlowConnection\nfrom metricflow.specs.query_specs import MetricFlowQuerySpec, MetricTimeDimension\nfrom metricflow.specs.metric_request import MetricRequest\nfrom metricflow.specs.dimension_spec import DimensionSpec\n\n# This quickstart demonstrates programmatic SQL generation for a minimal semantic model.\n# Actual execution requires a configured database connection.\n\n# 1. Create a dummy dbt project directory with a semantic model YAML file\ntemp_dir = Path(tempfile.mkdtemp())\ndbt_project_dir = temp_dir / \"my_dbt_project\"\ndbt_project_dir.mkdir()\n(dbt_project_dir / \"dbt_project.yml\").write_text(\"\"\"\nname: 'my_dbt_project'\nversion: '1.0.0'\nconfig-version: 2\nprofile: 'default'\n\"\"\")\n\nmodels_dir = dbt_project_dir / \"models\"\nmodels_dir.mkdir()\n(models_dir / \"my_semantic_model.yml\").write_text(\"\"\"\nsemantic_models:\n  - name: my_transactions_semantic_model\n    description: \"Transactions data\"\n    entities:\n      - name: user_id\n        type: primary\n    measures:\n      - name: sum_amount\n        agg: sum\n        expr: amount\n    dimensions:\n      - name: transaction_date\n        type: time\n        expr: created_at\n        time_granularity: day\n    metrics:\n      - name: total_revenue\n        calculation_config:\n          measure: sum_amount\n\"\"\")\n\n# 2. Configure MetricFlow by pointing to the dbt project\nmf_config = MetricFlowConfig(\n    dbt_project_path=str(dbt_project_dir)\n)\n\n# 3. Use NullMetricFlowConnection for generating SQL plans without executing against a real DB\nmf_connection = NullMetricFlowConnection()\n\n# 4. Initialize MetricFlowEngine\nengine = MetricFlowEngine(mf_config, mf_connection)\n\n# 5. Define a query for the 'total_revenue' metric, grouped by user_id and day\nmetric_requests = [\n    MetricRequest(metric_name=\"total_revenue\")\n]\ntime_dimension = MetricTimeDimension(\n    grain=\"day\",\n    date_spec=('2023-01-01', '2023-01-31')\n)\nquery_spec = MetricFlowQuerySpec(\n    metric_requests=metric_requests,\n    group_by_dimensions=[DimensionSpec(element_name=\"user_id\")],\n    time_dimension=time_dimension\n)\n\nprint(\"\\n--- Generating SQL Query Plan ---\")\ntry:\n    # plan_query returns the SQL query string for the given spec\n    query_plan_result = engine.plan_query(query_spec)\n    print(\"Generated SQL Query:\")\n    print(query_plan_result.sql_query)\n\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\nfinally:\n    # Clean up the temporary dbt project directory\n    shutil.rmtree(temp_dir)\n","lang":"python","description":"This quickstart demonstrates how to programmatically use MetricFlow to parse a semantic model definition and generate the corresponding SQL query. It sets up a minimal in-memory dbt project, configures the MetricFlow engine with a `NullMetricFlowConnection` to only generate a query plan (SQL) without execution. For actual data retrieval, replace `NullMetricFlowConnection` with a real database connection (e.g., `PostgresMetricFlowConnection`) and use `engine.query(query_spec)`."},"warnings":[{"fix":"Ensure your environment uses a supported Python version (3.9, 3.10, 3.11, or 3.12). Consider using `pyenv` or `conda` for environment management.","message":"MetricFlow has tight Python version requirements. Version 0.209.0 requires Python >=3.9 and <3.13. Using incompatible Python versions can lead to installation failures or runtime errors.","severity":"breaking","affected_versions":"<0.200.0 (older Python versions)"},{"fix":"Install MetricFlow in an isolated environment. If using with dbt-core, ensure your dbt-core version is compatible with the MetricFlow version, and let `pip` resolve transitive dependencies automatically where possible. Consult dbt's release notes for compatibility matrix.","message":"MetricFlow relies on specific versions of `dbt-common`, `dbt-extractor`, and `dbt-semantic-interfaces`. Upgrading these dependencies independently or with incompatible versions of dbt-core can cause dependency conflicts.","severity":"breaking","affected_versions":"All versions, especially major upgrades like 0.200.0"},{"fix":"Double-check exact spelling, casing, and hierarchy in your semantic model YAML. Ensure all referenced measures, entities, and dimensions are correctly defined and accessible within the semantic model's scope. Use the `mf validate` CLI command for early detection.","message":"Ambiguous semantic model definitions or incorrect metric/dimension names can lead to 'Metric not found' or 'Dimension not found' errors, even if the names appear correct in YAML.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Refer to the official dbt documentation for the latest MetricFlow semantic model syntax. Migrate your YAML definitions to the current standard. Use `mf validate` for syntax checks.","message":"The YAML syntax for defining semantic models and metrics has evolved. Older syntax (e.g., `primary_entity` instead of `entities`) or deprecated configurations might no longer be supported.","severity":"breaking","affected_versions":"Prior to 0.200.0"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Run `pip install metricflow` to install the package. If using virtual environments, ensure the correct environment is activated before running your script.","cause":"The `metricflow` package is not installed in the active Python environment, or the environment is not correctly activated.","error":"ModuleNotFoundError: No module named 'metricflow'"},{"fix":"Verify the exact spelling and casing of the metric name in your `MetricRequest` against its definition in your semantic model YAML. Ensure the `dbt_project_path` in `MetricFlowConfig` correctly points to your dbt project containing the semantic models.","cause":"The requested metric name does not exist in the loaded semantic manifest, or there's a typo in the name, or the semantic model file wasn't loaded correctly.","error":"Metric not found: 'my_metric_name'"},{"fix":"Ensure a `profiles.yml` file is present in your dbt profiles directory (usually `~/.dbt/`). Verify that the `profile` key in `dbt_project.yml` matches a profile in `profiles.yml`.","cause":"MetricFlow, like dbt, needs a `profiles.yml` file to connect to data warehouses. The specified profile (or the default 'default') is missing or misconfigured.","error":"dbt.exceptions.MissingProfileError: Could not find profile named 'default'"},{"fix":"Check the `measures` section of your semantic model YAML. Ensure that the `measure` referenced by a metric's `calculation_config` exists and is spelled correctly within that specific semantic model.","cause":"A metric's `calculation_config` references a measure that is not defined within the same semantic model, or the measure name is incorrect.","error":"metricflow.errors.MetricFlowException: Could not resolve measure 'some_measure' for metric 'some_metric'"}]}