home
diamond Go Premium
Data Engineering Path  ·  PySpark

RDD - Transformation SortByKey

The sortByKey() transformation is specialized for Key-Value Pair RDDs where each element is a tuple (key, value). It sorts the RDD elements based on the natural ordering of the keys (alphabetical, chronological, or numerical) in either ascending or descending order.


Performance Implications

Sorting requires a Wide Dependency. Spark must shuffle data across the network to group and sort elements by keys. To optimize this, Spark partitions the sorted data using a RangePartitioner, ensuring that elements in partition 1 are smaller than elements in partition 2, which allows sorting to occur independently within each partition block.


PySpark Code Examples

Setup Spark Session

from pyspark.sql import SparkSession

spark = SparkSession.builder \
    .appName("RDD Transformation SortByKey") \
    .master("local[*]") \
    .getOrCreate()

sc = spark.sparkContext

Example A: Sorting Alphabetical Keys (Ascending)

Let's sort a list of usernames alphabetically:

# 1. Input RDD of (Username, Score) tuples
user_scores = sc.parallelize([
    ("Charlie", 85),
    ("Alice", 99),
    ("Eve", 92),
    ("Bob", 78)
])

# 2. Sort keys in ascending order (default behavior)
sorted_users_asc = user_scores.sortByKey(ascending=True)

# 3. View final results
print("Sorted Users (Ascending):")
print(sorted_users_asc.collect())
# Output: [('Alice', 99), ('Bob', 78), ('Charlie', 85), ('Eve', 92)]

Example B: Sorting Numerical Keys (Descending)

Let's sort a list of transaction IDs in descending order:

# 1. Input RDD of (TransactionID, PurchaseAmount) tuples
transactions = sc.parallelize([
    (202, 54),
    (101, 120),
    (305, 15),
    (103, 90)
])

# 2. Sort by transaction ID keys descending
sorted_txns_desc = transactions.sortByKey(ascending=False)

print("Sorted Transactions (Descending):")
print(sorted_txns_desc.collect())
# Output: [(305, 15), (202, 54), (103, 90), (101, 120)]
Find this content helpful? ☕ Buy me a coffee

Entity Details

Create New Item

celebration
Enjoying the free content?

Create a free account to track your progress and save your place.

Create Free Account
help

Submit Technical Query

Have a question or run into an issue? Describe it below, upload an optional screenshot, and our engineering team will answer it!

image Attach image (optional)

Submit Feedback

build Free Developer Utility Free Tool
gavel

Privacy & Legal Disclaimer

1. Client-Side Browser Processing

All utility tools on DeepEngineerHub (including Image to PDF, Text Formatters, JSON Converters, and Encryptors) execute 100% locally within your client browser using WebAssembly and JavaScript. No uploaded images, text, or documents are transmitted, collected, or stored on remote servers.

2. Limitation of Liability ("As-Is" Provision)

Tools and services are provided free of charge for convenience and educational purposes "as-is" without warranties of any kind. DeepEngineerHub shall not be held liable for any data loss, formatting inconsistencies, or indirect damages resulting from tool usage.

3. Open Source & Third-Party Software

Certain utilities utilize open-source client libraries (such as jsPDF, Mermaid.js, Pyodide) licensed under MIT, Apache, or BSD open licenses. All intellectual property remains with their respective copyright holders.