Agregace v PySparku

Introduction to PySpark

Benjamin Schmidt

Data Engineer

Přehled agregací PySpark SQL

  • Běžné SQL agregace fungují s spark.sql()
    # SQL aggregation query
    spark.sql("""
      SELECT Department, SUM(Salary) AS Total_Salary, AVG(Salary) AS Average_Salary
      FROM employees
      GROUP BY Department
    """).show()
    
Introduction to PySpark

Kombinace operací DataFrame a SQL

# Filter salaries over 3000
filtered_df = df.filter(df.Salary > 3000)

# Register filtered DataFrame as a view
filtered_df.createOrReplaceTempView("filtered_employees")

# Aggregate using SQL on the filtered view spark.sql(""" SELECT Department, COUNT(*) AS Employee_Count FROM filtered_employees GROUP BY Department """).show()
Introduction to PySpark

Práce s datovými typy při agregacích

# Example of type casting
data = [("HR", "3000"), ("IT", "4000"), ("Finance", "3500")]
columns = ["Department", "Salary"]
df = spark.createDataFrame(data, schema=columns)

# Convert Salary column to integer df = df.withColumn("Salary", df["Salary"].cast("int")) # Perform aggregation df.groupBy("Department").sum("Salary").show()
Introduction to PySpark

Agregace pomocí RDD

# Example of aggregation with RDDs
rdd = df.rdd.map(lambda row: (row["Department"], row["Salary"]))

rdd_aggregated = rdd.reduceByKey(lambda x, y: x + y)
print(rdd_aggregated.collect())
Introduction to PySpark

Osvědčené postupy pro agregace v PySparku

  • Filtrujte včas: Zmenšete objem dat před agregací
  • Ošetřete datové typy: Zajistěte čistá a správně typovaná data
  • Vyhýbejte se operacím nad celým datasetem: Minimalizujte použití groupBy()
  • Zvolte správné rozhraní: Preferujte DataFrames díky jejich optimalizacím
  • Sledujte výkon: Použijte explain() k analýze a optimalizaci plánu vykonávání
Introduction to PySpark

Klíčové poznatky

  • Agregace PySpark SQL: Funkce jako SUM() a AVERAGE() pro sumarizaci dat
  • DataFrames a SQL: Kombinace obou přístupů pro flexibilní práci s daty
  • Datové typy: Řešení problémů s neshodou typů při agregacích
  • RDD vs. DataFrames: Pochopení kompromisů a volba správného nástroje
Introduction to PySpark

Pojďme cvičit!

Introduction to PySpark

Preparing Video For Download...