A production-ready implementation showing how to build AI-powered analytics with Databricks Metric Views, Genie, and Research Agent.
βββ data/ # Sample datasets
β βββ retail_transactions.csv # 100 transaction records
β βββ store_performance.csv # 100 store performance records
βββ src/metric_views/ # Metric View YAML definitions
β βββ retail_transactions_metric_view.yaml
β βββ retail_store_performance_metric_view.yaml
βββ docs/ # Documentation
β βββ linkedin_article_metric_views_genie.md
β βββ images/ # Architecture diagrams
βββ README.md # This file
- Databricks workspace with Unity Catalog enabled
- A catalog and schema where you have CREATE TABLE permissions
- Access to Databricks SQL or a cluster
# In a Databricks notebook
# Create a volume (if not exists)
spark.sql("""
CREATE VOLUME IF NOT EXISTS my_catalog.my_schema.raw_data
""")
# Upload files via UI: Catalog β Your Schema β Volumes β Upload Files
# Or use dbutils:
# dbutils.fs.cp("file:/local/path/retail_transactions.csv", "/Volumes/my_catalog/my_schema/raw_data/")# Transaction Data
df_transactions = (spark.read
.option("header", "true")
.option("inferSchema", "true")
.csv("/Volumes/my_catalog/my_schema/raw_data/retail_transactions.csv")
)
df_transactions.write.mode("overwrite").saveAsTable("my_catalog.my_schema.retail_business_table_1")
# Store Performance Data
df_performance = (spark.read
.option("header", "true")
.option("inferSchema", "true")
.csv("/Volumes/my_catalog/my_schema/raw_data/store_performance.csv")
)
df_performance.write.mode("overwrite").saveAsTable("my_catalog.my_schema.retail_business_table_2")COMMENT ON TABLE my_catalog.my_schema.retail_business_table_1 IS
'Transaction-level retail data including customer purchases, products, and payment methods';
COMMENT ON TABLE my_catalog.my_schema.retail_business_table_2 IS
'Monthly aggregated store performance metrics including revenue, costs, and profitability';- Navigate to Catalog β Your Schema
- Click Create β Metric View
- Copy the YAML from
src/metric_views/retail_transactions_metric_view.yaml - Important: Update the
sourceline to match your catalog/schema:source: my_catalog.my_schema.retail_business_table_1
- Click Create
Repeat for retail_store_performance_metric_view.yaml.
CREATE METRIC VIEW my_catalog.my_schema.retail_transactions_metrics
AS '
version: 1.1
source: my_catalog.my_schema.retail_business_table_1
dimensions:
- name: store_city
expr: StoreCity
comment: City where the store is located
- name: customer_segment
expr: CustomerSegment
comment: Customer loyalty segment
measures:
- name: total_revenue
expr: SUM(TotalAmount)
comment: Total revenue from all transactions
- name: transaction_count
expr: COUNT(*)
comment: Number of transactions
';GRANT SELECT ON METRIC VIEW my_catalog.my_schema.retail_transactions_metrics TO `analysts`;
GRANT SELECT ON METRIC VIEW my_catalog.my_schema.retail_store_performance_metrics TO `analysts`;- Navigate to Workspace β New β Genie Space
- Name: "Retail Analytics Assistant"
- Add data sources:
- Select your metric views from Unity Catalog
- Add instructions (optional):
You are a retail analytics assistant. - Customer segments: VIP, Premium, Regular, New - Profit margin target: 50% or higher is healthy - Cost-to-revenue ratio target: Below 0.45 is efficient - Click Create
Try these questions in your Genie Space:
| Question | Expected Result |
|---|---|
| "What was total revenue last month?" | Aggregated revenue |
| "Which stores have profit margins below 50%?" | Filtered store list |
| "Compare VIP vs Regular customer spending" | Segmented comparison |
| "Give me a 360 view of my business" | Comprehensive analysis |
In SQL Editor, create a new query:
SELECT
store_id,
city,
average_profit_margin,
cost_to_revenue_ratio
FROM my_catalog.my_schema.retail_store_performance_metrics
WHERE average_profit_margin < 45
OR cost_to_revenue_ratio > 0.55
ORDER BY average_profit_margin ASC- Save the query
- Click the Alert button (bell icon)
- Configure:
- Trigger: Query returns results
- Frequency: Every 1 hour
- Destination: Slack, Email, or Webhook
Research Agent is Genie's advanced analytical capability for answering "why" questions.
Ask questions like:
- "Why did Store STR008 profit margin drop?"
- "Analyze the revenue decline in Q3"
- "Explain the difference between top and bottom performing stores"
- Breaks down complex questions into sub-queries
- Investigates multiple dimensions and time periods
- Correlates findings across metrics
- Synthesizes insights with actionable recommendations
| Column | Type | Description |
|---|---|---|
| TransactionID | String | Unique transaction ID |
| StoreID | String | Store identifier (STR001-STR020) |
| StoreCity | String | City location |
| CustomerID | String | Customer identifier |
| CustomerSegment | String | VIP, Premium, Regular, New |
| TransactionDateTime | Timestamp | Transaction date/time |
| ProductID | String | Product code |
| ProductName | String | Product description |
| Category | String | Product category |
| Quantity | Integer | Items purchased |
| UnitPrice | Decimal | Price per unit |
| DiscountPercent | Decimal | Discount applied |
| TotalAmount | Decimal | Final amount |
| PaymentMethod | String | Payment type |
| Column | Type | Description |
|---|---|---|
| StoreID | String | Store identifier |
| City | String | Store location |
| Month | String | YYYY-MM format |
| MonthlyRevenue | Decimal | Total monthly revenue |
| MonthlyTransactions | Integer | Transaction count |
| AvgBasketSize | Decimal | Average basket value |
| UniqueCustomers | Integer | Unique customer count |
| EmployeeCount | Integer | Staff count |
| OperatingCosts | Decimal | Monthly costs |
| ProfitMarginPercent | Decimal | Profit margin % |
- Metric Views Overview
- Create Metric Views
- YAML Syntax Reference
- Databricks Genie
- Research Agent
- SQL Alerts
Feel free to open issues or submit PRs to improve the metric view definitions or add new use cases.
MIT License
Mehdi Wissad
Databricks Solution Architect
Built with β€οΈ using Databricks Metric Views, Genie & Research Agent