Reference library

Big data & Spark

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

18 matches
Big data & Spark easy

How to Broadcast a Small Lookup Table in Python

Simulates broadcasting a small lookup table by iterating key-value pairs and emitting packed rows to subscribers with deterministic output.

broadcast lookup-table dictionary
Python
import random

# Generate a deterministic mock broadcast of a small lookup table
# with 5 keys and random integer values (seeded for reproducibility)

data = {
    "sensor_a": 22,
    "sensor_b": 87,
    "sensor_c": 43,
    "sensor_d": 65,
    "sensor_e": 31,
}

# Simulate a broadcast to subscribers by iterating and p…
14 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 easy

How to Implement collect_list in Python

Group rows by a key and collect all corresponding values into a list — a pure-Python mock of Spark's collect_list aggregation.

collect_list aggregation grouping
Python
from collections import defaultdict

def collect_list(rows, key_field, value_field):
    grouped = defaultdict(list)
    for row in rows:
        grouped[row[key_field]].append(row[value_field])
    return dict(grouped)

if __name__ == "__main__":
    data = [
        {"dept": "sales", "emp": "alice"},
        {"dept"…
15 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 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 easy

How to Mock a Socket Stream in Python

Simulate a streaming socket source with a generator to test stream-read and buffering logic without a real network.

socket mock streaming
Python
import socket
import threading
import time

def mock_socket_stream(data_chunks, delay=0.1):
    """Generator that simulates a streaming socket source."""
    for chunk in data_chunks:
        time.sleep(delay)
        yield chunk

def read_stream_socket(stream_gen):
    """Reads from mock stream and prints received ch…
14 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 easy

How to Pivot and Group Aggregate in Python

Group records by a key, collect values, and apply an aggregate function (like sum) to build a pivot-style summary dictionary.

pivot group-by aggregation
Python
from collections import defaultdict

def pivot_group_aggregate(records, group_key, value_key, agg_func):
    groups = defaultdict(list)
    for record in records:
        groups[record[group_key]].append(record[value_key])
    return {key: agg_func(values) for key, values in groups.items()}

if __name__ == "__main__":…
13 0 Open
Big data & Spark easy

How to Shuffle Items by Group in Python

Randomly shuffle items within each group while keeping groups contiguous, using a seed for reproducible results.

random shuffle grouping
Python
import random

def shuffle_sort_groups(items, group_key, seed=None):
    """Randomize order within groups, keeping groups contiguous."""
    rng = random.Random(seed)
    
    groups = {}
    for item in items:
        key = group_key(item)
        groups.setdefault(key, []).append(item)
    
    result = []
    for k…
13 0 Open
Big data & Spark easy

How to Truncate Lineage Back to a Checkpoint in Python

Walks a linked list of lineage nodes upward to find the nearest checkpoint and returns that node, truncating the lineage.

lineage checkpoint linked-list
Python
class LineageNode:
    def __init__(self, name, parent=None, checkpoint=None):
        self.name = name
        self.parent = parent
        self.checkpoint = checkpoint

    def truncate_at_checkpoint(self):
        """Truncate lineage back to the last checkpoint."""
        current = self
        while current.check…
16 0 Open
Big data & Spark easy

How to Use Broadcast Variables as Read-Only in PySpark (Mock Example)

Share a lookup dict across Spark executors with a broadcast variable and verify its read-only behavior in a local mock.

pyspark broadcast spark
Python
from pyspark import SparkContext, SparkConf

def main():
    conf = SparkConf().setAppName("BroadcastMock").setMaster("local[2]")
    sc = SparkContext(conf=conf)
    
    lookup = {"a": 1, "b": 2, "c": 3}
    broadcast_lookup = sc.broadcast(lookup)
    
    data = ["a", "b", "c", "a", "unknown"]
    rdd = sc.parallel…
13 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

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.