본문으로 건너뛰기
cccskills
무료GitHub에 공개

spark-python-data-source

Build custom Python data sources for Apache Spark using the PySpark DataSource API — batch and streaming readers/writers for external systems. Use this skill whenever someone wants to connect Spark to an external system (database, API, message queue, custom protocol), build a Spark connector or plugin in Python, implement a DataSourceReader or DataSourceWriter, pull data from or push data to a system via Spark, or work with the PySpark DataSource API in any way. Even if they just say "read from X in Spark" or "write DataFrame to Y" and there's no native connector, this skill applies.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구HubSpot
설치 방법 보기

포함된 파일(12)

  • SKILL.md8.2 KB
  • agents/openai.yaml526 B
  • assets/databricks.png15.0 KB
  • assets/databricks.svg582 B
  • references/authentication-patterns.md10.5 KB
  • references/error-handling.md12.4 KB
  • references/implementation-template.md4.0 KB
  • references/partitioning-patterns.md10.7 KB
  • references/production-patterns.md11.4 KB
  • references/streaming-patterns.md12.7 KB
  • references/testing-patterns.md11.8 KB
  • references/type-conversion.md10.3 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

spark-python-data-source

Build custom Python data sources for Apache Spark 4.0+ to read from and write to external systems in batch and streaming modes.

Instructions

You are an experienced Spark developer building custom Python data sources using the PySpark DataSource API. Follow these principles and patterns.

Core Architecture

Each data source follows a flat, single-level inheritance structure:

  1. DataSource class — entry point that returns readers/writers
  2. Base Reader/Writer classes — shared logic for options and data processing
  3. Batch classes — inherit from base + DataSourceReader/DataSourceWriter
  4. Stream classes — inherit from base + DataSourceStreamReader/DataSourceStreamWriter

See implementation-template.md for the full annotated skeleton covering all four modes (batch read/write, stream read/write).

Spark-Specific Design Constraints

These are specific to the PySpark DataSource API and its driver/executor architecture — general Python best practices (clean code, minimal dependencies, no premature abstraction) still apply but aren't repeated here.

Flat single-level inheritance only. PySpark serializes reader/writer instances to ship them to executors. Complex inheritance hierarchies and abstract base classes break serialization and make cross-process debugging painful. Use one shared base class mixed with the PySpark interface (e.g., class YourBatchWriter(YourWriter, DataSourceWriter)).

Import third-party libraries inside executor methods. The read() and write() methods run on remote executor processes that don't share the driver's Python environment. Top-level imports from the driver won't be available on executors — always import libraries like requests or database drivers inside the methods that run on workers.

Minimize dependencies. Every package you add must be installed on all executor nodes in the cluster, not just the driver. Prefer the standard library; when external packages are needed, keep them few and well-known.

No async/await unless the external system's SDK is async-only. The PySpark DataSource API is synchronous, so async adds complexity with no benefit.

Project Setup

Create a Python project using a packaging tool such as uv, poetry, or hatch. Examples use uv (substitute your tool of choice):

uv init your-datasource
cd your-datasource
uv add pyspark pytest pytest-spark
your-datasource/
├── pyproject.toml
├── src/
│   └── your_datasource/
│       ├── __init__.py
│       └── datasource.py
└── tests/
    ├── conftest.py
    └── test_datasource.py

Run all commands through the packaging tool so they execute within the correct virtual environment:

uv run pytest                       # Run tests
uv run ruff check src/              # Lint
uv run ruff format src/             # Format
uv build                            # Build wheel

Key Implementation Decisions

Partitioning Strategy — choose based on data source characteristics:

  • Time-based: for APIs with temporal data
  • Token-range: for distributed databases
  • ID-range: for paginated APIs
  • See partitioning-patterns.md for implementations of each strategy

Authentication — support multiple methods in priority order:

  • Databricks Unity Catalog credentials
  • Cloud default credentials (managed identity)
  • Explicit credentials (service principal, API key, username/password)
  • See authentication-patterns.md for patterns with fallback chains

Type Conversion — map between Spark and external types:

  • Handle nulls, timestamps, UUIDs, collections
  • See type-conversion.md for bidirectional mapping tables and helpers

Streaming Offsets — design for exactly-once semantics:

  • JSON-serializable offset class
  • Non-overlapping partition boundaries
  • See streaming-patterns.md for offset tracking and watermark patterns

Error Handling — implement retries and resilience:

  • Exponential backoff for transient failures (network, rate limits)
  • Circuit breakers for cascading failures
  • See error-handling.md for retry decorators and failure classification

Testing

import pytest
from unittest.mock import patch, Mock

@pytest.fixture
def spark():
    from pyspark.sql import SparkSession
    return SparkSession.builder.master("local[2]").getOrCreate()

def test_data_source_name():
    assert YourDataSource.name() == "your-format"

def test_writer_sends_data(spark):
    with patch('requests.post') as mock_post:
        mock_post.return_value = Mock(status_code=200)

        df = spark.createDataFrame([(1, "test")], ["id", "value"])
        df.write.format("your-format").option("url", "http://api").save()

        assert mock_post.called

See testing-patterns.md for unit/integration test patterns, fixtures, and running tests.

Reference Implementations

Study these for real-world patterns:

Example Prompts

Create a Spark data source for reading from MongoDB with sharding support
Build a streaming connector for RabbitMQ with at-least-once delivery
Implement a batch writer for Snowflake with staged uploads
Write a data source for REST API with OAuth2 authentication and pagination

Related

  • databricks-testing: Test data sources on Databricks clusters
  • databricks-spark-declarative-pipelines: Use custom sources in DLT pipelines
  • python-dev: Python development best practices

References

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Create Agent Bricks: Knowledge Assistants (KA) for document Q&A and Supervisor Agents for multi-agent orchestration (MAS).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

databricks/databricks-agent-skills3542026년 10월 19일 업데이트

Use Databricks built-in AI Functions (ai_classify, ai_extract, ai_summarize, ai_mask, ai_translate, ai_fix_grammar, ai_gen, ai_analyze_sentiment, ai_similarity, ai_parse_document, ai_prep_search, ai_query, ai_forecast) to add AI capabilities directly to SQL and PySpark pipelines without managing model endpoints. Also covers document parsing and building custom RAG pipelines (parse → prep_search → index → query).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

databricks/databricks-agent-skills3542026년 10월 19일 업데이트

Databricks AI Runtime, the `databricks air` CLI commands for submitting and managing GPU training workloads on Databricks serverless compute. Use for: writing and submitting `databricks air` workload YAML, passing hyperparameters and secrets, checking run status, listing/cancelling runs, streaming a run's logs and watching its progress, custom Docker image setup, and environment configuration.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

databricks/databricks-agent-skills3542026년 10월 19일 업데이트

Create Databricks AI/BI dashboards. Must use when creating, updating, or deploying Lakeview dashboards as Databricks Dashboard have a unique json structure. CRITICAL: You MUST test ALL SQL queries via CLI BEFORE deploying. Follow guidelines strictly.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

databricks/databricks-agent-skills3542026년 10월 19일 업데이트

Design the UX of custom-code Databricks Apps (AppKit/React) data screens — KPI/overview pages, reports, charts, tables, and Genie/chat data assistants — mapped to concrete AppKit components. Use when BUILDING or reviewing the UI of an AppKit/React app that displays data or answers data questions: choosing genre, layout, charts, KPIs, semantic color, required states (loading/empty/error), IBCS notation, and AI-result trust (showing generated SQL/sources for Genie/chat). A plain "create a dashboard" request means a managed AI/BI (Lakeview) dashboard → use databricks-aibi-dashboards, NOT this skill. Also NOT for non-data frontend (forms, settings, auth, marketing) or scaffolding/build/deploy (→ databricks-apps). Complements databricks-apps; use it alongside whenever a custom app has a chart, table, KPI, report, or Genie/chat/AI surface.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

databricks/databricks-agent-skills3542026년 10월 19일 업데이트

Build apps on Databricks Apps platform. Use when asked to create data apps, analytics tools, or custom interactive visualizations. A plain "create a dashboard" request means a managed AI/BI (Lakeview) dashboard → use databricks-aibi-dashboards, not this skill. Evaluates data access patterns (analytics vs Lakebase synced tables) before scaffolding. Invoke BEFORE starting implementation.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

databricks/databricks-agent-skills3542026년 10월 19일 업데이트

databricks의 스킬 모두 보기

이 스킬의 문제 신고