Built with Tutify.io

    AIStudyLabs

    Creating Views & Tables

    Creating Views & Tables

    Introduction

    One of the main advantages of Apache Spark is working with SQL along with the DataFrame/Dataset API. If you are comfortable with SQL, you can create a temporary view on DataFrame/Dataset by using createOrReplaceTempView() and use SQL to select and manipulate the data.

    A Temporary view in Spark is similar to a real SQL table that contains rows and columns, but the view is not materialized into files. In this article, we will discuss what createOrReplaceTempView() is, and how to use it to create a temporary view and run Spark SQL queries.

    Note that throughout this article, the terms table and view will be used interchangeably.

    1. Syntax of createOrReplaceTempView()

    Following is the syntax of the createOrReplaceTempView() method. This method is from the Dataset class, so you can use this method from Spark DataFrame and Dataset objects.

    // Syntax of createOrReplaceTempView()
    void createOrReplaceTempView(String viewName);
    

    2. How Does createOrReplaceTempView() work in Spark?

    createOrReplaceTempView() in Spark creates a view only if it does not exist; if it exists, it replaces the existing view with the new one. Spark SQL views are lazily evaluated, meaning they do not persist in memory unless you cache the dataset by using the cache() method.

    Some key points to note:

    3. Create a Temporary View

    The createOrReplaceTempView() is used to create a temporary view/table from the Spark DataFrame or Dataset objects. Since it is a temporary view, the lifetime of the table/view is tied to the current SparkSession. Hence, it will be automatically removed when your Spark session ends.

    If you are using an older version prior to Spark 2.0, you can use registerTempTable() to create a temporary table.

    Following are the steps to create a temporary view in Spark and access it.

    3.1 Create a DataFrame

    First, let’s create a Spark DataFrame with columns firstname, lastname, country, and state.

    // Create DataFrame
    SparkSession spark = SparkSession.builder()
        .master("local[1]")
        .appName("AIStudyLabs.com")
        .getOrCreate();
    
    List<Row> data = Arrays.asList(
        RowFactory.create("James", "Smith", "USA", "CA"),
        RowFactory.create("Michael", "Rose", "USA", "NY"),
        RowFactory.create("Robert", "Williams", "USA", "CA"),
        RowFactory.create("Maria", "Jones", "USA", "FL")
    );
    
    StructType schema = new StructType(new StructField[]{
        new StructField("firstname", DataTypes.StringType, false, Metadata.empty()),
        new StructField("lastname", DataTypes.StringType, false, Metadata.empty()),
        new StructField("country", DataTypes.StringType, false, Metadata.empty()),
        new StructField("state", DataTypes.StringType, false, Metadata.empty())
    });
    
    Dataset<Row> df = spark.createDataFrame(data, schema);
    df.show(false);
    

    3.2 Create Table/View using Spark createOrReplaceTempView()

    Let’s create a temporary view on top of the DataFrame object by using df.createOrReplaceTempView(). Spark SQL temporary views are session-scoped and will not be available if the session that creates them terminates. The following example creates a Person table.

    // Create Temporary View/Table
    df.createOrReplaceTempView("Person");
    

    If you want to have a temporary view that is shared among all sessions and kept alive until the Spark application terminates, you can create a global temporary view using createGlobalTempView().

    3.3 Access View using Spark SQL Query

    Using SparkSession, you can access Spark SQL capabilities in Apache Spark. Once you have a temporary view, you can run any ANSI SQL queries using the spark.sql() method.

    // Run SQL Query
    spark.sql("select firstname, lastname from Person").show();
    

    Yields the following output.

    +---------+--------+
    |firstname|lastname|
    +---------+--------+
    |    James|   Smith|
    |  Michael|    Rose|
    |   Robert|Williams|
    |    Maria|   Jones|
    +---------+--------+
    

    Apache Spark Tutorial with Java Examples — Advanced DataFrame Features

    Introduction to Apache Spark

    Setup Apache Spark Environment

    SparkSession & SparkContext

    Resilient Distributed Datasets (RDDs)

    Cache, Persistence and Shared Variables

    DataFrame Introduction

    DataFrame Narrow Transformation

    DataFrame Wider Transformation

    DataFrame Actions

    Spark SQL Functions

    Advanced DataFrame Features

    Using SQL Queries

    Spark Read & Write CSV Files

    Working with JSON Files

    Working with Parquet Files

    Spark Dataset

    What Next?

    Tutorial Not Found