Introduzione a Spark SQL

Introduzione a PySpark

Benjamin Schmidt

Data Engineer

Cos'è Spark SQL

  • Modulo di Apache Spark per elaborare dati strutturati
  • Permette di eseguire query SQL insieme a compiti di elaborazione dati
  • Combina Python e SQL in un'unica applicazione
  • Interfaccia DataFrame: Accesso programmato ai dati strutturati
Introduzione a PySpark

Creare tabelle temporanee

# Inizializza la sessione Spark
spark = SparkSession.builder.appName("Spark SQL Example").getOrCreate()

# DataFrame di esempio data = [("Alice", "HR", 30), ("Bob", "IT", 40), ("Cathy", "HR", 28)] columns = ["Name", "Department", "Age"] df = spark.createDataFrame(data, schema=columns)
# Registra il DataFrame come vista temporanea df.createOrReplaceTempView("people")
# Query usando SQL result = spark.sql("SELECT Name, Age FROM people WHERE Age > 30") result.show()
Introduzione a PySpark

Approfondiamo le viste temporanee

  • Le viste temporanee proteggono i dati durante l'analisi
  • Caricare da un CSV usa metodi già noti
    df = spark.read.csv("path/to/your/file.csv", header=True, inferSchema=True)
    
# Registra il DataFrame come vista temporanea
df.createOrReplaceTempView("employees")
Introduzione a PySpark

Combinare operazioni SQL e DataFrame

# Risultato della query SQL
query_result = spark.sql("SELECT Name, Salary FROM employees WHERE Salary > 3000")

# Trasformazione DataFrame high_earners = query_result.withColumn("Bonus", query_result.Salary * 0.1) high_earners.show()
Introduzione a PySpark

Facciamo pratica!

Introduzione a PySpark

Preparing Video For Download...