Reference library

Big data & Spark

PySpark jobs, partitioning, batch processing, and large-dataset transform patterns.

30 matches
Big data & Spark medium

Approximate Distinct Count in Python with HyperLogLog

Mock a large data stream and estimate the number of distinct items with a HyperLogLog-style probabilistic counter to save memory.

hyperloglog distinct-count probabilistic
Python
import random
import string
from collections import Counter
import math

class ApproxCountDistinct:
    def __init__(self, num_buckets=16):
        self.num_buckets = num_buckets
        self.max_zeros = [0] * num_buckets
        
    def _hash(self, item):
        # Simple string hash to a 32-bit integer
        h = …
15 0 Open
Big data & Spark medium

Bloom Filter Join Mock in Python

A mock hash join that uses a Bloom filter to pre-filter one table before performing an exact match, reducing the number of comparisons in large dataset joins.

bloom filter join hashing
Python
import hashlib
import random
import string


class BloomFilter:
    def __init__(self, size: int = 200, num_hashes: int = 3):
        self.bits = [False] * size
        self.size = size
        self.num_hashes = num_hashes

    def _hashes(self, item: str):
        result = []
        for seed in range(self.num_hashes…
13 0 Open
Big data & Spark easy

Cache persist MEMORY_ONLY mock in Python

Mock a MEMORY_ONLY persistence cache in Python with an LRU eviction policy and optional persistence flag.

cache lru mock
Python
import time

class LRUCache:
    def __init__(self, capacity, persistence="MEMORY_ONLY"):
        self.capacity = capacity
        self.persistence = persistence
        self.cache = {}
        self.access_order = []
        self.hits = 0
        self.misses = 0

    def get(self, key):
        if key in self.cache:
 …
13 0 Open
Big data & Spark easy

Compaction Small Files Mock in Python

Simulates a small-files compaction job by creating small mock files and merging them into a single output file using Python's standard library.

compaction file-io mock
Python
from pathlib import Path
import tempfile
import os


def create_small_files(directory: Path, file_count: int = 5, lines_per_file: int = 3):
    """Create several small mock files with sample content."""
    directory.mkdir(exist_ok=True)
    for i in range(file_count):
        file_path = directory / f"part-{i:04d}.tx…
17 0 Open
Big data & Spark medium

Delta Lake ACID Transaction Log Mock in Python

Simulates Delta Lake's transactional log with JSON files for atomic commits, versioned operations, and crash recovery

delta-lake transaction-log acid
Python
import json
import time
from pathlib import Path

class DeltaLog:
    def __init__(self, path):
        self.log_dir = Path(path)
        self.log_dir.mkdir(parents=True, exist_ok=True)
        self.version = 0

    def _write_txn(self, action, payload):
        txn = {
            "version": self.version,
           …
16 0 Open
Big data & Spark medium

How to Create a Mock Iceberg Snapshot Manifest in Python

Build a mock Iceberg snapshot manifest structure with metadata and data entries using Python dictionaries and JSON.

iceberg manifest snapshot
Python
import json
from datetime import datetime, timezone


def create_mock_manifest(snapshot_id: int, file_paths: list[str]) -> dict:
    """Create a mock Iceberg snapshot manifest structure."""
    manifest_file = {
        "manifest_path": f"/warehouse/table/metadata/snap-{snapshot_id}-m0.avro",
        "manifest_length"…
15 0 Open
Big data & Spark easy

How to Create a Mock Kafka Producer in Python

Build a Kafka producer that generates mock streaming records with JSON serialization and error handling for local testing.

kafka streaming producer
Python
import json
import time
from kafka import KafkaProducer
from kafka.errors import KafkaError

def create_mock_producer(bootstrap_servers="localhost:9092", topic="input-topic"):
    """Create a Kafka producer that generates mock streaming data."""
    producer = KafkaProducer(
        bootstrap_servers=bootstrap_servers…
16 0 Open
Big data & Spark easy

How to Explode an Array Column in Python

This code demonstrates a mock explode operation that converts an array column into multiple rows, similar to Spark's explode function.

explode arrays pyspark
Python
import json 

def explode_array_column(data, column):
    """Mock explode: split array column into multiple rows."""
    exploded = []
    for row in data:
        values = row.get(column, [])
        for value in values:
            new_row = dict(row)
            new_row[column] = value
            exploded.append(n…
13 0 Open
Big data & Spark easy

How to Filter and Project Spark DataFrames with PySpark SQL

Simulate a SQL SELECT with WHERE using PySpark DataFrame select and filter to project columns and apply conditions.

pyspark dataframe filter
Python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.appName("QueryFilterMock").master("local[2]").getOrCreate()

data = [
    ("Alice", 28, "Engineering"),
    ("Bob", 35, "Sales"),
    ("Carol", 32, "Engineering"),
    ("David", 25, "Marketing"),
    ("Eve", 29, "E…
14 0 Open
Big data & Spark easy

How to Implement MapReduce Word Count in Python Using a Dict

Simulate a MapReduce word count pipeline in Python with a mock dict, splitting text into words, shuffling, and reducing to frequency counts.

mapreduce word-count dictionary
Python
def map_reduce_word_count(text: str) -> dict:
    """Simulate a MapReduce pipeline to count word frequencies."""
    # MAP phase: split into words and emit (word, 1) pairs
    mapped = []
    for word in text.lower().split():
        # Clean word of punctuation
        clean_word = ''.join(char for char in word if cha…
16 0 Open
Big data & Spark medium

How to Implement a Mock MapReduce for Word Count in Python

Simulates a MapReduce word count pipeline with mapper, shuffle, and reducer phases using Python dicts and standard library modules.

mapreduce word-count big-data
Python
from collections import defaultdict
import re

def mapper(text):
    """Split text into words and emit (word, 1) pairs."""
    words = re.findall(r'\b\w+\b', text.lower())
    return [(word, 1) for word in words]

def reducer(pairs):
    """Group word-count pairs and sum counts."""
    counts = defaultdict(int)
    fo…
15 0 Open
Big data & Spark medium

How to Implement row_number Window Function in Python

This code implements a SQL-style ROW_NUMBER() window function in pure Python, partitioning rows by a set of columns and ranking them within each partition by an ordered set of columns.

window-functions data-processing row-number
Python
from collections import defaultdict
import itertools


def row_number(rows, partition_by, order_by):
    partitions = defaultdict(list)
    for index, row in enumerate(rows):
        key = tuple(row[col] for col in partition_by)
        partitions[key].append((index, row))

    result = []
    for key in partitions:
 …
17 0 Open
Big data & Spark easy

How to Mock DataFrame Schema Columns in Python

Create an empty pandas DataFrame with only the specified column names to mock a schema before any data is loaded.

pandas dataframe schema
Python
import pandas as pd

def mock_schema(columns):
    return pd.DataFrame(columns=columns)

if __name__ == "__main__":
    cols = ["name", "age", "city"]
    df = mock_schema(cols)
    print(df)
    print(f"Columns: {list(df.columns)}, Shape: {df.shape}")
14 0 Open
Big data & Spark easy

How to Mock Hive Support in PySpark with unittest.mock

This code demonstrates how to mock Hive support in a PySpark environment using unittest.mock to simulate SQL queries returning fixed data.

pyspark hive mock
Python
from unittest.mock import Mock, patch


def get_hive_tables(spark):
    """Mock Hive support by returning a fixed list of tables."""
    return spark.sql("SHOW TABLES").collect()


class HiveTable:
    """Simple class that mimics a Hive table row."""
    def __init__(self, database, tableName):
        self.database =…
14 0 Open
Big data & Spark easy

How to Mock Partition Pruning in Python

A dataclass-based mock that filters partitions by year and month to emulate Spark's partition pruning logic.

spark partition dataclass
Python
from dataclasses import dataclass
from typing import List


@dataclass(frozen=True)
class Partition:
    id: int
    year: int
    month: int


class PartitionPruner:
    """Mock partition pruning: only keep partitions that match the filter."""
    def __init__(self, partitions: List[Partition]):
        self._partiti…
15 0 Open
Big data & Spark medium

How to Mock a Catalyst Logical Plan in Python

Build a small Python class that mimics Spark Catalyst's logical plan tree for teaching or testing query optimizations.

apache-spark logical-plan catalyst
Python
from typing import Any, Dict, List, Optional


class CatalystLogicalPlan:
    """A minimal mock of Catalyst's logical plan for teaching purposes."""
    
    def __init__(self, node_type: str, **kwargs: Any) -> None:
        self.node_type = node_type
        self.attributes: Dict[str, Any] = kwargs
        self.child…
13 0 Open
Big data & Spark easy

How to Mock a File Source Watch Directory in Python

Poll a directory for new files and log changes, simulating a watch directory for data ingestion patterns.

file-watching polling etl
Python
import os
import time
from pathlib import Path


def watch_directory(dir_path: str, poll_interval: float = 1.0, max_iterations: int = 5):
    """
    Mock a file-source watch directory by polling for changes.
    Returns new files detected during each poll cycle.
    """
    directory = Path(dir_path)
    directory.mk…
15 0 Open
Big data & Spark easy

How to Mock a Hash Join on Large and Small Tables in Python

This code efficiently joins a large dataset (1000 rows) with a small lookup table (20 rows) by building a dictionary hash lookup, mimicking a hash join strategy used in big data systems.

hash-join dictionaries data-join
Python
import random
from pprint import pprint

# Large table: 1000 rows (id, group_id, value)
large = [{"id": i, "group_id": random.randint(1, 20), "value": random.random() * 100} for i in range(1000)]

# Small table: 20 rows (group_id, label)
small = [{"group_id": g, "label": f"Group-{g}"} for g in range(1, 21)]

# Mock a …
13 0 Open
Big data & Spark medium

How to Mock a Parquet partitionBy Sink in Python

Manually write a DataFrame to partitioned Parquet files, mimicking Spark's partitionBy sink behavior without Spark.

parquet pyarrow partition
Python
import pyarrow as pa
import pyarrow.parquet as pq
from pathlib import Path
import tempfile
import shutil


def mock_partition_by_sink(data, output_dir, partition_cols):
    table = pa.Table.from_pandas(data)
    schema = table.schema
    unique_combos = table.select(partition_cols).to_pylist()
    seen = set()
    for…
13 0 Open
Big data & Spark easy

How to Mock a User-Defined Function (UDF) in Python

Wrap a real UDF implementation with call logging to simulate and track invocations in a data pipeline.

udf mock testing
Python
from typing import Any, Callable


# Mock a user-defined function (UDF) that was previously complex or external
def mock_udf(name: str, implementation: Callable[..., Any], *, calls: list[Any]) -> Callable[..., Any]:
    """Wrap a real implementation with call logging to simulate a UDF."""
    def wrapper(*args: Any, *…
13 0 Open
Big data & Spark medium

How to Simulate a MapReduce Mock with Combine Phase in Python

Simulates a MapReduce pipeline with a combiner that aggregates local counts per reducer to reduce network and compute overhead.

mapreduce combiner hadoop
Python
from collections import defaultdict

def map_phase(lines):
    intermediate = defaultdict(list)
    for line in lines:
        for word in line.strip().lower().split():
            intermediate[word].append(1)
    return dict(intermediate)

def combine_phase(intermediate, num_reducers=3):
    combined = defaultdict(li…
14 0 Open
Big data & Spark easy

How to select specific columns in Python with SQLite

A reusable function that connects to a SQLite database and returns only the requested columns from a given table.

sqlite sql database
Python
import sqlite3

def select_pruned_columns(db_path, table, columns):
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        col_list = ", ".join(columns)
        query = f"SELECT {col_list} FROM {table}"
        return cursor.execute(query).fetchall()

if __name__ == "__main__":
    conn = sq…
15 0 Open
Big data & Spark easy

Hudi Upsert Mock Copy on Write in Python

Simulates Apache Hudi's Copy-on-Write upsert behavior by merging update records into a deep copy of base records, replacing matches or appending new ones.

hudi upsert copy-on-write
Python
import copy
from typing import Dict, List, Any

def upsert_copy_on_write(base_records: List[Dict[str, Any]], updates: List[Dict[str, Any]], key_field: str = "id") -> List[Dict[str, Any]]:
    """Simulate Hudi Copy-on-Write upsert: merge updates into a copy of base records."""
    result = copy.deepcopy(base_records)
 …
14 0 Open
Big data & Spark medium

Lazy Evaluation Transform Lineage Mock in Python

Build a mock lineage tracker for data transforms using lazy evaluation and function wrappers in Python.

lazy-evaluation lineage decorator
Python
import functools


def lazy_transform(pipeline):
    """Build a mock lineage tracker using lazy evaluation."""
    lineage = []

    def wrap(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            lineage.append({"transform": func.__name__, "a…
16 0 Open

Browse by section

Each section groups closely related Python snippets.

Big data & Spark — Python code examples

What you will find here

This page collects big data & spark snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.