Spark SQL

You should go through the Spark SQL Guide
before beginning this section.

This section requires an additioal dependency on Spark SQL:

  1. <dependency> <!-- Spark SQL -->
  2. <groupId>org.apache.spark</groupId>
  3. <artifactId>spark-sql_2.11</artifactId>
  4. <version>2.0.1</version>
  5. </dependency>

For those of you who are familiar with SQL, the same statistics we calculated
in the previous example can be done using Spark SQL rather than calling
Spark transformations and actions directly. We walk through how to do that
here.

First, we need to create a SparkSession instance - an entry point for every Spark SQL application.
Using SparkSession, we read a text file and obtain a Dataset of Strings,
where every string represents a line from the input file. Finally, we convert the
Dataset of Strings to Dataset of ApacheAccessLog entries.
To become familiar with Dataset concept, refer to
Datasets and DataFrames

  1. public class LogAnalyzerSQL {
  2. public static void main(String[] args) {
  3. // Initialize SparkSession instance.
  4. SparkSession sparkSession = SparkSession
  5. .builder()
  6. .appName("Log Analyzer SQL")
  7. .getOrCreate();
  8. JavaSparkContext sc = new JavaSparkContext(sparkSession.sparkContext());
  9. if (args.length == 0) {
  10. System.out.println("Must specify an access logs file.");
  11. System.exit(-1);
  12. }
  13. String logFile = args[0];
  14. // Read Dataset of lines from the file.
  15. // Note how we convert Dataset of String lines to Dataset of ApacheAccessLog objects
  16. // using an Encoder.
  17. Dataset<ApacheAccessLog> accessLogs = sparkSession
  18. .read()
  19. .textFile(logFile)
  20. .map(ApacheAccessLog::parseFromLogLine,
  21. Encoders.bean(ApacheAccessLog.class));
  22. // TODO: Insert code for computing log stats.
  23. sc.stop();
  24. }
  25. }

Next, we register our logs data into a view in order to run SQL
queries on it.

  1. // Register the Dataset as a temporary view.
  2. accessLogs.createOrReplaceTempView("logs");

Now, we are ready to start running some SQL queries on our view. Here’s
the code to compute the identical statistics in the previous section - it
should look very familiar for those of you who know SQL. For transformations
on Datasets, Spark SQL uses Encoders. The API provides Encoders for all
widely used datatypes, as well as utilities to create Encoders for composite
data types like tuples.

  1. // Calculate statistics based on the content size.
  2. Row contentSizeStats = sparkSession
  3. .sql("SELECT SUM(contentSize), COUNT(*), MIN(contentSize), MAX(contentSize) FROM logs")
  4. .first();
  5. System.out.println(String.format("Content Size Avg: %s, Min: %s, Max: %s",
  6. contentSizeStats.getLong(0) / contentSizeStats.getLong(1),
  7. contentSizeStats.getLong(2),
  8. contentSizeStats.getLong(3)));
  9. // Compute Response Code to Count.
  10. // Note the use of "LIMIT 1000" since the number of responseCodes
  11. // can potentially be too large to fit in memory.
  12. List<Tuple2<Integer, Long>> responseCodeToCount = sparkSession
  13. .sql("SELECT responseCode, COUNT(*) FROM logs GROUP BY responseCode LIMIT 100")
  14. .map(row -> new Tuple2<>(row.getInt(0), row.getLong(1)),
  15. Encoders.tuple(Encoders.INT(), Encoders.LONG()))
  16. .collectAsList();
  17. System.out.println(String.format("Response code counts: %s", responseCodeToCount));
  18. // Any IPAddress that has accessed the server more than 10 times.
  19. List<String> ipAddresses = sparkSession
  20. .sql("SELECT ipAddress, COUNT(*) AS total FROM logs GROUP BY ipAddress HAVING total > 10 LIMIT 100")
  21. .map(row -> row.getString(0), Encoders.STRING())
  22. .collectAsList();
  23. System.out.println(String.format("IPAddresses > 10 times: %s", ipAddresses));
  24. // Top Endpoints.
  25. List<Tuple2<String, Long>> topEndpoints = sparkSession
  26. .sql("SELECT endpoint, COUNT(*) AS total FROM logs GROUP BY endpoint ORDER BY total DESC LIMIT 10")
  27. .map(row -> new Tuple2<>(row.getString(0), row.getLong(1)),
  28. Encoders.tuple(Encoders.STRING(), Encoders.LONG()))
  29. .collectAsList();
  30. System.out.println(String.format("Top Endpoints: %s", topEndpoints));

Note that the default SQL dialect does not allow using reserved keyworks as alias names. In other words, SELECT COUNT(*) AS count will cause errors, but SELECT COUNT(*) AS the_count runs fine. If you use the HiveQL parser though, then you should be able to use anything as an identifier.

Try running LogAnalyzerSQL.java now.