Book consult
    Azure

    Databricks Unity Catalog: Data Governance at Scale

    Prasanna Ravikumar
    October 23, 2024
    Databricks Unity Catalog: Data Governance at Scale

    Learn how Databricks Unity Catalog provides centralized governance, fine-grained access control, and data lineage for lakehouse architectures across clouds.

    Databricks Unity Catalog: Data Governance at Scale

    Databricks Unity Catalog represents a paradigm shift in data governance for lakehouse architectures, providing centralized metadata management, fine-grained access control, and comprehensive data lineage across multi-cloud environments.

    What is Unity Catalog?

    Unity Catalog is a unified governance solution for all data and AI assets on Databricks. It provides:

    - Centralized Metadata - Single source of truth for all data assets - Fine-Grained Access Control - Column and row-level security - Data Lineage - Automatic tracking from source to consumption - Audit Logging - Comprehensive access audit trails - Multi-Cloud Support - Works across Azure, AWS, and GCP

    Why Unity Catalog Matters

    Traditional Challenges

    Before Unity Catalog: - Workspace-isolated metastores - Inconsistent security across workspaces - No centralized governance - Manual lineage tracking - Complex multi-cloud management

    With Unity Catalog: - Account-level metastore - Consistent security policies - Centralized governance - Automatic lineage - Unified multi-cloud view

    Architecture Overview

    Three-Level Namespace

    ``` Metastore (Account Level) | +-- Catalog (Database Container) | +-- Schema (Namespace) | +-- Tables, Views, Functions ```

    Example: ```sql SELECT FROM prod_catalog.sales.customer_orders; -- [catalog] [schema] [table] ```

    Managed vs External Tables

    Managed Tables: - Unity Catalog manages data and metadata - Data stored in managed storage location - Dropping table deletes data

    External Tables: - Data stored in external location - Unity Catalog manages metadata only - Dropping table keeps data

    Setting Up Unity Catalog

    Step 1: Create Metastore

    ```sql -- Metastore created at account level (via UI or API) -- One per region recommended ```

    Step 2: Create Catalog

    ```sql CREATE CATALOG IF NOT EXISTS sales_analytics COMMENT 'Analytics catalog for sales data';

    USE CATALOG sales_analytics; ```

    Step 3: Create Schema

    ```sql CREATE SCHEMA IF NOT EXISTS prod COMMENT 'Production sales data';

    CREATE SCHEMA IF NOT EXISTS staging COMMENT 'Staging area for data ingestion'; ```

    Step 4: Create Tables

    ```sql -- Managed table CREATE TABLE sales_analytics.prod.customers ( customer_id BIGINT, first_name STRING, last_name STRING, email STRING, created_at TIMESTAMP ) COMMENT 'Customer master data';

    -- External table CREATE EXTERNAL TABLE sales_analytics.staging.raw_events LOCATION 'abfss://landing@mydatalake.dfs.core.windows.net/events'; ```

    Access Control

    Grant Privileges

    ```sql -- Grant catalog access GRANT USE CATALOG ON CATALOG sales_analytics TO data_analysts;

    -- Grant schema access GRANT USE SCHEMA ON SCHEMA sales_analytics.prod TO data_analysts;

    -- Grant table select GRANT SELECT ON TABLE sales_analytics.prod.customers TO data_analysts;

    -- Grant all privileges GRANT ALL PRIVILEGES ON CATALOG sales_analytics TO data_engineers; ```

    Revoke Privileges

    ```sql REVOKE SELECT ON TABLE sales_analytics.prod.customers FROM data_analysts; ```

    Row-Level Security

    ```sql -- Create row filter function CREATE FUNCTION sales_analytics.prod.customer_filter(region STRING) RETURN IF(IS_MEMBER('regional_managers'), TRUE, region = current_user());

    -- Apply row filter ALTER TABLE sales_analytics.prod.customers SET ROW FILTER sales_analytics.prod.customer_filter ON (region); ```

    Column-Level Security

    ```sql -- Create column mask function CREATE FUNCTION sales_analytics.prod.ssn_mask(ssn STRING) RETURN CASE WHEN IS_MEMBER('pii_readers') THEN ssn ELSE 'XXX-XX-' || RIGHT(ssn, 4) END;

    -- Apply column mask ALTER TABLE sales_analytics.prod.customers ALTER COLUMN ssn SET MASK sales_analytics.prod.ssn_mask; ```

    External Locations

    Create External Location

    ```sql -- Create storage credential (via UI or API) CREATE STORAGE CREDENTIAL azure_storage_cred WITH (AZURE_MANAGED_IDENTITY);

    -- Create external location CREATE EXTERNAL LOCATION data_lake_bronze URL 'abfss://bronze@mydatalake.dfs.core.windows.net/' WITH (STORAGE CREDENTIAL azure_storage_cred) COMMENT 'Bronze layer for raw data';

    -- Grant access GRANT CREATE TABLE ON EXTERNAL LOCATION data_lake_bronze TO data_engineers; ```

    Data Lineage

    Automatic Lineage Tracking

    Unity Catalog automatically tracks: - Table-to-table lineage - Column-level lineage - Notebook lineage - Dashboard lineage

    Query Lineage Example

    ```sql -- This query creates automatic lineage CREATE OR REPLACE TABLE sales_analytics.prod.customer_summary AS SELECT c.customer_id, c.first_name, c.last_name, COUNT(o.order_id) as total_orders, SUM(o.amount) as total_spent FROM sales_analytics.prod.customers c LEFT JOIN sales_analytics.prod.orders o ON c.customer_id = o.customer_id GROUP BY c.customer_id, c.first_name, c.last_name;

    -- Lineage tracked: -- customers → customer_summary -- orders → customer_summary ```

    View Lineage

    ```python In Databricks notebook from databricks.sdk import WorkspaceClient

    w = WorkspaceClient()

    Get table lineage lineage = w.table_lineage.get( table_name='sales_analytics.prod.customer_summary' )

    print(lineage) ```

    Delta Sharing

    Share Data Across Organizations

    ```sql -- Create share CREATE SHARE customer_data_share;

    -- Add tables to share ALTER SHARE customer_data_share ADD TABLE sales_analytics.prod.customers COMMENT 'Shared customer data';

    -- Grant access to recipient GRANT SELECT ON SHARE customer_data_share TO RECIPIENT partner_org; ```

    Consume Shared Data

    ```sql -- Create catalog from share CREATE CATALOG shared_data USING SHARE provider.customer_data_share;

    -- Query shared data SELECT FROM shared_data.default.customers; ```

    Data Discovery

    Search and Tag Assets

    ```sql -- Add tags to tables ALTER TABLE sales_analytics.prod.customers SET TAGS ('pii' = 'true', 'department' = 'sales');

    -- Add comments COMMENT ON TABLE sales_analytics.prod.customers IS 'Master customer table with PII data';

    COMMENT ON COLUMN sales_analytics.prod.customers.email IS 'Customer email address (PII)'; ```

    Search Using Data Explorer

    ```python Search via API from databricks.sdk import WorkspaceClient

    w = WorkspaceClient()

    Search for tables results = w.tables.list( catalog_name='sales_analytics', schema_name='prod' )

    for table in results: print(f'{table.name}: {table.comment}') ```

    Audit Logging

    Enable Audit Logs

    ```sql -- Audit logs automatically enabled -- Access via system tables ```

    Query Audit Logs

    ```sql -- View table access SELECT event_time, user_identity.email as user_email, action_name, request_params.full_name_arg as table_name FROM system.access.audit WHERE action_name = 'getTable' AND event_date >= current_date() - 7 ORDER BY event_time DESC; ```

    Migration Strategies

    Migrate from Hive Metastore

    ```sql -- Upgrade table to Unity Catalog CREATE TABLE sales_analytics.prod.customers_migrated DEEP CLONE hive_metastore.default.customers;

    -- Or use SYNC SYNC TABLE sales_analytics.prod.customers FROM hive_metastore.default.customers; ```

    Bulk Migration

    ```python Python script for bulk migration from databricks.sdk import WorkspaceClient

    w = WorkspaceClient()

    List Hive tables hive_tables = spark.sql("SHOW TABLES IN hive_metastore.default").collect()

    Migrate each table for table in hive_tables: table_name = table['tableName'] spark.sql(f""" CREATE TABLE sales_analytics.prod.{table_name} DEEP CLONE hive_metastore.default.{table_name} """) print(f"Migrated {table_name}") ```

    Best Practices

    Naming Conventions

    Catalogs: - Environment-based: `dev`, `staging`, `prod` - Domain-based: `sales`, `marketing`, `finance`

    Schemas: - Layer-based: `bronze`, `silver`, `gold` - Function-based: `raw`, `curated`, `analytics`

    Tables: - Descriptive names: `customer_orders`, `product_inventory` - Include date for snapshots: `customers_20240101`

    Security Principles

    1. Least Privilege - Grant minimum required access 2. Separation of Duties - Different roles for different tasks 3. Regular Audits - Review access logs regularly 4. Data Classification - Tag and classify sensitive data 5. Encryption - Enable encryption at rest and in transit

    Performance Optimization

    Table Properties: ```sql ALTER TABLE sales_analytics.prod.customers SET TBLPROPERTIES ( 'delta.autoOptimize.optimizeWrite' = 'true', 'delta.autoOptimize.autoCompact' = 'true' ); ```

    Partitioning: ```sql CREATE TABLE sales_analytics.prod.orders ( order_id BIGINT, customer_id BIGINT, order_date DATE, amount DECIMAL(10,2) ) PARTITIONED BY (order_date); ```

    Monitoring and Troubleshooting

    Monitor Usage

    ```sql -- Query system tables SELECT table_catalog, table_schema, table_name, COUNT() as query_count FROM system.access.table_lineage WHERE event_date >= current_date() - 30 GROUP BY table_catalog, table_schema, table_name ORDER BY query_count DESC; ```

    Common Issues

    Permission Denied: - Check catalog, schema, and table grants - Verify user group membership - Review row/column filters

    Lineage Not Showing: - Ensure queries use three-level namespace - Check Unity Catalog is enabled - Allow time for lineage propagation

    Advanced Features

    Dynamic Views

    ```sql CREATE VIEW sales_analytics.prod.filtered_customers AS SELECT FROM sales_analytics.prod.customers WHERE region = current_user() OR IS_MEMBER('admin'); ```

    Materialized Views (Coming Soon)

    ```sql CREATE MATERIALIZED VIEW sales_analytics.prod.daily_sales AS SELECT DATE(order_timestamp) as order_date, SUM(amount) as total_sales FROM sales_analytics.prod.orders GROUP BY DATE(order_timestamp); ```

    Integration with Other Tools

    Power BI Integration

    ```python Connect Power BI to Unity Catalog tables Use Databricks SQL connector Leverage row/column security ```

    Azure Purview Integration

    - Automatic asset registration - Unified governance across Azure - Enhanced data discovery

    Conclusion

    Databricks Unity Catalog provides enterprise-grade governance for modern data architectures. By centralizing metadata, enforcing fine-grained access control, and automatically tracking lineage, it enables organizations to govern their data at scale while maintaining agility.

    Key Takeaways: - Implement three-level namespace for organization - Use fine-grained access control (row/column level) - Leverage automatic lineage tracking - Enable Delta Sharing for collaboration - Monitor access with audit logs - Migrate systematically from Hive metastore

    With Unity Catalog, you can build a governed lakehouse that scales with your organization while meeting compliance and security requirements.

    Share this article