pyspark-etl
БесплатноБез исполняемых скриптовНе проверенBest practices for building performant, testable PySpark ETL pipelines with Spark SQL and Apache Iceberg. Use when writing or reviewing PySpark jobs…
от Mindrally★ 323 звезды на GitHubОб этом скилле
PySpark ETL
This skill covers patterns for building production-grade, testable ETL pipelines with PySpark, Spark SQL, and Apache Iceberg, including project structure, join and window-function idioms, and safe cumulative-table merge patterns.
Workflow for Building a PySpark ETL Job
- Scaffold the job class — Create a class that manages the
SparkSessionlifecycle, accepts an injectable session for testing, and exposes an abstractrun_jobmethod. - Define config via a factory function — Keep config as a plain dataclass; parse CLI args in a separate factory function so tests can construct configs without touching
sys.argv. - Read source data with a shared, partition-aware reader — Use a generic reader utility for date filters, hour ranges, and latest-partition lookups; keep business filters in the ETL class.
- Compose the pipeline with
.transform()— Chain named methods (read_source().transform(self.enrich).transform(self.merge_with_existing)) sorun_jobstays pure orchestration. - Apply transformations idiomatically — Use
selectoverwithColumnchains, explicit join types, explicit window frames, and native functions instead of UDFs. - Write with schema-evolution safety — Use
.byName()when writing to Iceberg tables so column order doesn't matter. - Validate output — Check primary-key uniqueness and null counts on key columns after every write.
- Test locally — Unit test transformation methods against a local
SparkSessionwith small, hand-built DataFrames.
Project Structure
ETL class scaffold
from abc import ABC, abstractmethod
import logging
from pyspark.sql import SparkSession
class BaseETL(ABC):
def __init__(self, config, app_name="ETL Job", spark_session=None):
self.spark = spark_session or SparkSession.builder.appName(app_name).getOrCreate()
self.config = config
self.logger = logging.getLogger(self.__class__.__name__)
@abstractmethod
def run_job(self): ...
def stop(self):
self.spark.stop()
Config as a factory function
Keep the dataclass as pure data; put CLI parsing in a standalone factory so configs are easy to build in tests.
import argparse
from dataclasses import dataclass
@dataclass
class MyConfig:
read_date: int = 20260101
def create_config() -> MyConfig:
parser = argparse.ArgumentParser()
parser.add_argument("--read_date", type=int, default=20260101)
args = parser.parse_args()
return MyConfig(read_date=args.read_date)
Partition-aware shared reader
Build one generic reader for partition mechanics; keep domain-specific filters visible in the ETL, not buried in a one-off reader class.
import pyspark.sql.functions as F
class PartitionedReader:
@staticmethod
def read_latest(spark, table_name, partition_col):
row = spark.read.table(table_name).agg(F.max(partition_col)).first()
if row is None or row[0] is None:
return spark.createDataFrame([], spark.read.table(table_name).schema)
return spark.read.table(table_name).filter(F.col(partition_col) == row[0])
@staticmethod
def read_by_date(spark, table_name, partition_col, date_value):
return spark.read.table(table_name).filter(F.col(partition_col) == date_value)
events = PartitionedReader.read_by_date(spark, "catalog.my_table", "event_date", 20260319)
events = events.filter(F.col("event_type").isin("login", "purchase"))
Code Style
- Import functions as
import pyspark.sql.functions as Fand always useF.col()instead ofdf.colAattribute access — attribute access binds a column to a specific DataFrame variable and breaks after joins or reassignment. - Extract complex boolean logic inside
.filter()orF.when()into named variables once it exceeds 3 expressions. - Prefer
selectover chains ofwithColumn—selectstates the output schema in one pass, while eachwithColumncall adds a projection to the query plan. - Use
.alias()instead ofwithColumnRenamed. - Limit chained method calls to 5 per statement; separate
select/filterchains fromwithColumnchains fromjoinchains by operation type.
# BAD — 3 intermediate DataFrames, one projection per call
df = df.withColumn("a", F.col("a").cast("double"))
df = df.withColumn("b", F.upper(F.col("b")))
df = df.withColumn("c", F.lit(1))
# GOOD — one DataFrame, explicit schema contract
df = df.select(
F.col("a").cast("double"),
F.upper(F.col("b")).alias("b"),
F.lit(1).alias("c"),
)
Joins
- Always specify
how=explicitly — never rely on the default. - Prefer left joins over right joins for readability; flip DataFrame order instead of using
how="right". - Alias whole DataFrames for disambiguation after joins rather than renaming every column with
withColumnRenamed. - Wrap small dimension/lookup tables in
F.broadcast()when joining against a large fact table, especially after filters or
Установить pyspark-etl в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл pyspark-etl?
Best practices for building performant, testable PySpark ETL pipelines with Spark SQL and Apache Iceberg. Use when writing or reviewing PySpark jobs, designing joins and window functions, working with map/array higher-order functions, or building idempotent cumulative/snapshot table merges.
Как установить скилл pyspark-etl?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл pyspark-etl запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic