|
| 1 | +package com.techmonad.learn |
| 2 | + |
| 3 | +import org.apache.spark.sql.DataFrame |
| 4 | +import org.apache.spark.sql.functions._ |
| 5 | + |
| 6 | +object DataFrameOps extends SparkSessionProvider { |
| 7 | + |
| 8 | + def main(args: Array[String]): Unit = { |
| 9 | + |
| 10 | + val df: DataFrame = |
| 11 | + spark |
| 12 | + .read |
| 13 | + .text("data/words.txt") |
| 14 | + println("###############Word Count################") |
| 15 | + val wordCounts = |
| 16 | + df |
| 17 | + .withColumn("words", split(col("value"), "\\s+")) |
| 18 | + .withColumn("word", explode(col("words"))) |
| 19 | + .select("word") |
| 20 | + .groupBy("word") |
| 21 | + .agg(count("word").as("count")) |
| 22 | + wordCounts.show() |
| 23 | + |
| 24 | + // Joins |
| 25 | + val users = |
| 26 | + spark |
| 27 | + .read |
| 28 | + .option("delimiter", ",") |
| 29 | + .option("header", "true") |
| 30 | + .csv("data/users.csv") |
| 31 | + users.show() |
| 32 | + |
| 33 | + val userDetails = |
| 34 | + spark |
| 35 | + .read |
| 36 | + .option("header", "true") |
| 37 | + .option("delimiter", ",") |
| 38 | + .csv("data/user-details.csv") |
| 39 | + |
| 40 | + userDetails.show() |
| 41 | + |
| 42 | + println("#############Inner Join###################") |
| 43 | + val innerJoin: DataFrame = users.join(userDetails, Seq("id"), "inner") |
| 44 | + innerJoin.show() |
| 45 | + |
| 46 | + println("#############Left Join###################") |
| 47 | + val leftJoin: DataFrame = users.join(userDetails, Seq("id"), "left") |
| 48 | + leftJoin.show() |
| 49 | + |
| 50 | + println("#############Right Join###################") |
| 51 | + val rightJoin: DataFrame = users.join(userDetails, Seq("id"), "right") |
| 52 | + rightJoin.show() |
| 53 | + |
| 54 | + |
| 55 | + println("#############full Join###################") |
| 56 | + val fullJoin: DataFrame = users.join(userDetails, Seq("id"), "full") |
| 57 | + fullJoin.show() |
| 58 | + |
| 59 | + spark.stop() |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments