算法艺术创作
algorithmic-art
通过代码和可调参数创作生成艺术与交互式视觉效果。
data-data-lakehouse【设计与创意】Use this skill when designing lakehouse architectures with medallion layers (bronze/silver/gold), Databricks Unity Catalog, Delta Sharing, Apache Paimon, or multi-cloud lakehouse. This skill enforces: medallion architecture layers and data flow, Unity Catalog metastore and RBAC, Delta Sharing for data mesh, Apache Paimon table format, multi-cloud rep…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Design lakehouse architectures that merge data lake flexibility with warehouse reliability. Implement medallion architecture for data quality progression, Unity Catalog for governance, Delta Sharing for data collaboration, and multi-cloud deployment patterns.
Exact user phrases: "lakehouse", "medallion architecture", "bronze", "silver", "gold", "Databricks", "Unity Catalog", "Delta Sharing", "Apache Paimon", "multi-cloud lakehouse", "open formats", "lakehouse governance", "data mesh lakehouse".
Before activating, verify:
Lakehouse architecture with medallion layers, Unity Catalog configuration, and platform deployment specs.
Lakehouse Platform: {Databricks | EMR + Iceberg | Synapse + Delta | Dataproc + Iceberg}
Catalog: {Unity Catalog | Hive Metastore | AWS Glue | Nessie}
Table Format: {Delta | Iceberg | Paimon}
Medallion Layers: Bronze (raw), Silver (cleaned), Gold (aggregated)
Sharing: {Delta Sharing | open | proprietary}
# Unity Catalog metastore config
# Medallion pipeline YAML
No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.
300 lines of code and configuration.
Bronze: raw ingested data, schema-on-read, append-only, preserves original format. Silver: cleaned, deduplicated, validated, partitioned, CDC applied. Gold: aggregated, joined, business-level KPIs, consumption-ready for BI and ML.
Bronze fails are quarantined (dead-letter). Silver fails are logged and alerted. Gold fails block dashboard refresh.
Define retention per layer: Bronze 30-90 days raw, Silver 90-365 days cleaned, Gold 365+ days aggregated. Use different storage classes per layer (Bronze on standard, Gold on SSD-accelerated).
-- Bronze table (append-only)
CREATE TABLE bronze.events (
event_id STRING, event_type STRING, payload STRUCT<...>,
ingest_time TIMESTAMP, source_file STRING
) USING DELTA
TBLPROPERTIES ('delta.appendOnly' = 'true');
-- Silver table (deduplicated)
CREATE TABLE silver.events (
event_id STRING, event_type STRING, ...,
valid_from TIMESTAMP, valid_to TIMESTAMP, is_current BOOLEAN
) USING DELTA
TBLPROPERTIES ('delta.feature.timestampNtz' = 'true');
Metastore: top-level container for metadata, maps to cloud storage location. Catalog: logical database grouping (e.g., prod, dev, analytics). Schema: namespace within catalog (e.g., bronze, silver, gold). Tables, views, functions, models.
-- Unity Catalog DDL
CREATE CATALOG IF NOT EXISTS retail;
USE CATALOG retail;
CREATE SCHEMA IF NOT EXISTS bronze;
CREATE SCHEMA IF NOT EXISTS silver;
CREATE SCHEMA IF NOT EXISTS gold;
-- Grant permissions
GRANT USAGE ON CATALOG retail TO `domain-commerce`;
GRANT SELECT ON SCHEMA retail.silver TO `domain-analytics`;
GRANT MODIFY ON SCHEMA retail.bronze TO `data-engineers`;
-- Row filter
CREATE OR REPLACE FUNCTION retail.filter_pii()
RETURN filter_condition AS "region = current_user_region()";
ALTER TABLE silver.customers SET ROW FILTER retail.filter_pii ON (region);
Open protocol for secure data sharing between Delta Lake tables. No data copy — recipient gets read-only access to pre-signed URLs.
-- Create a share
CREATE SHARE IF NOT EXISTS retail_share;
ALTER SHARE retail_share ADD TABLE retail.gold.daily_revenue;
ALTER SHARE retail_share ADD TABLE retail.gold.top_products;
-- Create recipient
CREATE RECIPIENT IF NOT EXISTS partner_analytics
USING AUTHENTICATION TYPE DATABRICKS;
GRANT SELECT ON SHARE retail_share TO RECIPIENT partner_analytics;
Delta Sharing protocol is open and implemented by Databricks, OSS Delta Lake, Apache Spark, Pandas, and PowerBI. Recipients do not need Databricks — they only need the Delta Sharing client library.
Unified streaming and batch lake format built for Flink. Uses LSM tree for high-throughput writes. Supports primary keys, partial updates, sequence groups.
-- Paimon table with primary key
CREATE TABLE paimon.orders (
order_id STRING, status STRING, total DOUBLE, ts TIMESTAMP(3)
) WITH (
'bucket' = '4',
'bucket-key' = 'order_id',
'merge-engine' = 'deduplicate',
'changelog-producer' = 'input',
'snapshot.time-retained' = '72h'
);
Paimon bucket count should be a factor of the parallelism. Bucket = max(parallelism / 2, 1). For append-only tables, use no bucket key and higher bucket count for write parallelism.
Single pane of glass across AWS, Azure, GCP. Delta as universal format, Unity Catalog as centralized metadata, object store replication (S3 -> ADLS -> GCS).
multi_cloud_setup:
primary_cloud: aws
secondary_clouds: [azure, gcp]
replication_mode: active_passive
replication_tool: delta-sharing
catalog: unity_catalog
table_format: delta
sync_frequency: hourly
failover_rto: 30_minutes
failover_rpo: 1_hour
Replication strategies: Delta Sharing for cross-cloud reads, cloud-native tools (S3 replication, AzCopy, gsutil) for storage-level sync, and Delta Live Tables for active-active replication. Prefer Delta Sharing for simplicity — it gives recipients direct read access without data movement.
Bronze: ensure files readable, schema matches, no empty payloads. Silver: null rate <5% on key columns, referential integrity, dedup by business key. Gold: aggregate totals match across dimensions, historical trend consistent.
# Quality gate at silver layer
from pyspark.sql import functions as F
silver_checks = {
"null_rate": df.filter(F.col("order_id").isNull()).count() == 0,
"dup_rate": df.count() == df.select("order_id").distinct().count(),
"freshness": df.agg(F.max("created_at")).collect()[0][0] > cutoff,
"volume": df.count() > expected_min_rows,
}
Quality gate failures: Bronze → dead-letter queue for replay. Silver → alert domain owner, block downstream. Gold → rollback to previous snapshot, page on-call.
Vacuum: remove old files not in transaction log (7-day retention). Optimize: Z-order on high-cardinality filter columns. Partitioning: date columns for time-range queries. Liquid clustering: adaptive clustering without explicit partition management.
OPTIMIZE silver.orders ZORDER BY (customer_id, order_date);
VACUUM silver.orders RETAIN 168 HOURS;
ALTER TABLE silver.orders CLUSTER BY (customer_id, order_date);
-- Auto-compaction (Delta)
ALTER TABLE silver.orders SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true'
);
Apache XTable enables format interoperability — keep a single data copy while exposing it as Delta, Iceberg, or Hudi. Nessie adds Git-like version control to Iceberg tables for catalog-level branching, tagging, and time travel.
XTable syncs metadata across formats without copying data. Use when you have multi-engine environments: Spark on Delta, Trino on Iceberg, Flink on Hudi. Nessie enables atomic multi-table commits and branch-based development workflows for data engineering teams.
LSM flow: MemTable -> flush to L0 -> compaction into sorted L1+ runs. Merge engines: deduplicate, partial-update, aggregation, first-row. Changelog producers track row-level changes.
Paimon's LSM compaction is configurable: num-sorted-run-stop-trigger (default 5), num-sorted-run-max-size (default 50), max-compacted-files (default 50). Tune for write-heavy vs read-heavy workloads. Write-heavy: increase stop-trigger, reduce max-compacted-files. Read-heavy: decrease stop-trigger, increase max-compacted-files.
Track bronze ingestion lag, silver dedup rate, gold freshness compliance, query latency per engine, storage cost per layer, and Unity Catalog access patterns.
-- Monitor table size and file count
DESCRIBE EXTENDED silver.orders;
-- Check Delta history
DESCRIBE HISTORY silver.orders LIMIT 10;
-- Vacuum and optimize stats (Databricks)
SELECT * FROM system.table_metrics
WHERE table_name = 'silver.orders';
Unity Catalog automatically captures column-level lineage when using Databricks. Lineage is visible in Catalog Explorer and queryable via system tables. Enable lineage tracking on all production catalogs. Use system tables for access audit: system.access.databricks_access and system.access.table_lineage.
Federate queries across multiple lakehouse instances using Trino or Databricks Lakehouse Federation. Register external data sources (PostgreSQL, Snowflake, MySQL, SQL Server) as foreign catalogs in Unity Catalog. This enables queries that join lakehouse data with operational databases without data movement.
New lakehouse table
├── Databricks ecosystem? → Delta Lake
├── Multi-engine (Trino, Spark, Flink)? → Iceberg
├── Streaming + batch on Flink? → Apache Paimon
├── Existing Hive/Hadoop? → Hudi
└── Need format interoperability? → XTable to expose as multiple formats
Raw data arrives
├── Append-only log, no transformation? → Bronze only
├── Needs dedup + validation? → Bronze → Silver
├── Needs aggregation + business logic? → Bronze → Silver → Gold
└── Direct consumption from source? → Skip bronze, use Silver
Deploy lakehouse
├── Already on AWS
│ ├── Need managed Spark? → AWS EMR + Iceberg
│ └── Need simplicity? → Databricks on AWS
├── Already on Azure
│ ├── Microsoft stack? → Azure Synapse + Delta
│ └── Open-source? → Databricks on Azure
├── Already on GCP
│ ├── Need managed? → Databricks on GCP
│ └── Prefer native? → Dataproc + Iceberg
└── Multi-cloud → Databricks + Delta + Unity Catalog
| Feature | Databricks Lakehouse | AWS Lake Formation | Azure Synapse | GCP Dataproc + Iceberg |
|---|---|---|---|---|
| Table format | Delta Lake | Parquet + Glue | Delta | Iceberg |
| Catalog | Unity Catalog | AWS Glue | Purview | Hive Metastore / Dataproc |
| Sharing | Delta Sharing | LF-Tagged | Azure Data Share | BigQuery Analytics Hub |
| Multi-cloud | Yes | No | No | No |
| Streaming | Structured Streaming | Kinesis | Stream Analytics | Dataflow |
| ML integration | MLflow, Feature Store | SageMaker | Azure ML | Vertex AI |
| RBAC | Catalog-level | Lake Formation | AAD RBAC | IAM + Dataproc |
| Open format | Delta (OSS) | Parquet | Delta | Iceberg (OSS) |
| Self-hosted | No | No | No | Yes |
Lakehouse vs data warehouse: lakehouse uses open formats and object storage, warehouse uses proprietary storage engines. Lakehouse is更适合 for ML and data science; warehouse excels at BI and SQL analytics. Many organizations run both.
Lakehouse vs data lake: lakehouse adds ACID transactions, schema enforcement, and performance optimization (indexing, caching, clustering). A data lake is just storage — a lakehouse is storage + table format + catalog + compute.
Scalability considerations: Bronze layer scales horizontally with object storage (no compute bottleneck). Silver and Gold are compute-bound — provision auto-scaling clusters. For petabyte-scale bronze, partition by source + date and use batch ingestion windows. For Unity Catalog, each metastore supports up to 10,000 tables. Use multiple metastores for larger deployments.
| Tool | Purpose |
|---|---|
| Databricks | Unified lakehouse platform |
| Apache Spark | Batch and streaming compute |
| Delta Lake | Table format with ACID |
| Apache Iceberg | Open table format, multi-engine |
| Apache Paimon | Streaming + batch lake format |
| Unity Catalog | Centralized governance |
| Delta Sharing | Inter-org data sharing |
| Apache XTable | Format interoperability |
| Nessie | Catalog-level version control |
| AWS Glue / Hive Metastore | External catalog |
| Apache Flink | Streaming engine for Paimon |
| Trino / Starburst | Federated SQL query engine |
| dbt | Data transformation, contract enforcement |
| Soda / Monte Carlo | Data observability and quality |
| Delta Live Tables (DLT) | Declarative ETL pipelines |
# Query engine optimization by workload
optimization:
bi_dashboards:
engine: "Databricks SQL Warehouse (serverless)"
config:
- use_photon: true # Vectorized engine (2-10x faster)
- warehouse_size: "SMALL to LARGE" # Scale based on concurrency
- auto_stop: 15min
- min_clusters: 1
- max_clusters: 5
tips:
- "Create materialized views on gold tables"
- "Use Databricks SQL with Photon for dashboard queries"
- "Result caching for repeated query patterns"
- "Aggregate at gold layer — avoid detail-level queries in BI"
ml_training:
engine: "Spark (Python DataFrame API)"
config:
- "Use Delta format for training data reads"
- "Enable Delta caching for repeated data access"
- "Auto-optimize: target file size 256MB"
tips:
- "Extract training data from gold layer"
- "Use point-in-time joins for feature computation"
- "Persist intermediate results as Delta tables"
ad_hoc_exploration:
engine: "Databricks Notebooks + Spark SQL"
config:
- "Use Databricks SQL for SQL exploration"
- "Pandas on Spark for Python exploration"
- "Auto-scaling clusters for concurrent ad-hoc queries"
tips:
- "Set query timeout (5min default for exploration)"
- "Use sample tables for initial exploration"
- "Tag expensive queries for cost tracking"
streaming:
engine: "Structured Streaming (Spark)"
config:
- "Auto-compact on streaming tables"
- "Trigger interval: 1-60 seconds based on latency needs"
- "Output mode: append for fact tables, update for aggregates"
tips:
- "Use merge-on-read for update-heavy streams"
- "Set bronze retention to match stream reprocessing window"
- "Monitor streaming lag through Delta change data feed"
lakehouse_platforms:
databricks:
description: "Unified analytics platform (original lakehouse)"
catalog: "Unity Catalog"
formats: "Delta Lake (native), Iceberg, Hudi"
engines: "Spark, Databricks SQL, Photon"
ml_integration: "MLflow, Feature Store, Model Serving"
strengths: ["Best Delta Lake support", "Unity Catalog", "Photon", "ML integration"]
weaknesses: ["DBU cost at scale", "Vendor lock-in concerns"]
apache_iceberg:
description: "Open table format with broad engine support"
catalog: "Nessie, Hive, JDBC, REST, Glue"
formats: "Iceberg"
engines: "Spark, Trino, Flink, Hive, Presto, Dremio"
ml_integration: "Via Spark/Python"
strengths: ["Most open ecosystem", "Partition evolution", "Multi-engine"]
weaknesses: ["Less mature governance vs Unity Catalog", "Self-managed catalog"]
aws_sagemaker_lakehouse:
description: "AWS lakehouse with SageMaker + Athena + Iceberg"
catalog: "Glue Catalog"
formats: "Iceberg (via Athena), Delta (via Spark)"
engines: "Athena, Spark on EMR, Redshift Spectrum"
ml_integration: "SageMaker"
strengths: ["AWS-native", "Serverless Athena queries", "Low cost"]
weaknesses: ["Decoupled components", "Less integrated than Databricks"]
Primary ecosystem?
├── Databricks ecosystem, need unified ML + BI
│ └── Databricks with Delta Lake + Unity Catalog
├── Open-source, multi-engine, non-Databricks
│ └── Apache Iceberg with Nessie/REST catalog + Trino/Spark
├── AWS-native, tight AWS integration
│ └── AWS Lake Formation + Iceberg + Athena/EMR
├── Google Cloud-native
│ └── BigLake + Iceberg + BigQuery/Dataproc
└── Multi-cloud, avoid vendor lock-in
└── Apache Iceberg (most portable table format)
Lakehouse Architecture Selection
├── Medallion architecture (bronze/silver/gold)?
│ ├── Yes → Delta Lake / Iceberg with medallion layers
│ └── No → Direct ingestion to gold/pre-aggregated
├── Multi-cloud or hybrid?
│ ├── Yes → Iceberg (cloud-agnostic)
│ ├── AWS-native → Delta Lake on S3
│ └── Azure-native → Delta Lake on ADLS
├── BI tool compatibility priority?
│ ├── Yes → Delta Lake (BI native support)
│ └── No → Iceberg (broader engine support)
└── Streaming + batch convergence?
├── Yes → Delta Live Tables / PyIceberg streaming
└── No → Batch-only lakehouse
Decision criteria: Assess cloud strategy, engine ecosystem (Spark, Trino, DuckDB), streaming needs, and team expertise with table formats.
# data_lakehouse/medallion_pipeline.py
from pyspark.sql import SparkSession, DataFrame
class MedallionPipeline:
def __init__(self, spark: SparkSession, catalog: str, database: str):
self.spark = spark
self.catalog = catalog
self.database = database
def bronze_layer(self, source_path: str, table: str) -> DataFrame:
df = self.spark.read.format("json").load(source_path)
df.writeTo(f"{self.catalog}.{self.database}.bronze_{table}") \
.tableProperty("format-version", "2") \
.createOrReplace()
return df
def silver_layer(self, bronze_table: str, silver_table: str, transformations: list) -> DataFrame:
df = self.spark.table(f"{self.catalog}.{self.database}.{bronze_table}")
for t in transformations:
df = t(df)
df.writeTo(f"{self.catalog}.{self.database}.{silver_table}") \
.partitionedBy("ingestion_date") \
.createOrReplace()
return df
def gold_layer(self, silver_table: str, gold_table: str, agg_cols: list, metric: str):
df = self.spark.table(f"{self.catalog}.{self.database}.{silver_table}")
aggs = df.groupBy(*agg_cols).agg({metric: "SUM"})
aggs.writeTo(f"{self.catalog}.{self.database}.{gold_table}").createOrReplace()
# data_lakehouse/catalog_sync.yml
sync:
source: nessie
target: aws_glue
tables:
- silver.orders
- gold.revenue_daily
schedule: "0 */6 * * *"
conflict_resolution: source_wins
expire_snapshots and rewrite_data_files / Delta VACUUM and OPTIMIZE as weekly jobs.| Anti-Pattern | Consequence | Solution |
|---|---|---|
| No medallion layering | Direct ingestion creates unmanageable lake | Adopt bronze/silver/gold pattern |
| Cross-engine format incompatibility | Queries fail on different engines | Test Iceberg with all query engines |
| Ignoring orphan file cleanup | Storage costs balloon without benefit | Run vacuum after every compaction |
| No catalog redundancy | Single point of failure for metadata | Deploy Nessie + Glue fallback |
| Over-partitioning gold tables | Too many small files in aggregates | Coalesce gold tables by day/week |
table_changes) for downstream consumers instead of full scans.GRANT/REVOKE on table/catalog level.data-data-lake for underlying table format operations (compaction, vacuum, Z-order)
data-distributed-storage for S3-compatible storage backend configuration
data-data-quality for validation rules and data contract enforcement