Skip to content
Snippets Groups Projects
sql-programming-guide.md 96.8 KiB
Newer Older
  • Learn to ignore specific revisions
  • {% include_example json_dataset java/org/apache/spark/examples/sql/JavaSQLDataSourceExample.java %}
    
    </div>
    
    <div data-lang="python"  markdown="1">
    
    Spark SQL can automatically infer the schema of a JSON dataset and load it as a DataFrame.
    
    This conversion can be done using `SparkSession.read.json` on a JSON file.
    
    Note that the file that is offered as _a json file_ is not a typical JSON file. Each
    
    line must contain a separate, self-contained valid JSON object. For more information, please see
    
    [JSON Lines text format, also called newline-delimited JSON](http://jsonlines.org/).
    
    
    For a regular multi-line JSON file, set the `multiLine` parameter to `True`.
    
    {% include_example json_dataset python/sql/datasource.py %}
    
    Spark SQL can automatically infer the schema of a JSON dataset and load it as a DataFrame. using
    
    the `read.json()` function, which loads data from a directory of JSON files where each line of the
    
    Note that the file that is offered as _a json file_ is not a typical JSON file. Each
    
    line must contain a separate, self-contained valid JSON object. For more information, please see
    
    [JSON Lines text format, also called newline-delimited JSON](http://jsonlines.org/).
    
    
    For a regular multi-line JSON file, set a named parameter `multiLine` to `TRUE`.
    
    {% include_example json_dataset r/RSparkSQLExample.R %}
    
    <div data-lang="sql"  markdown="1">
    
    {% highlight sql %}
    
    
    USING org.apache.spark.sql.json
    OPTIONS (
      path "examples/src/main/resources/people.json"
    )
    
    SELECT * FROM jsonTable
    
    {% endhighlight %}
    
    </div>
    
    
    
    Spark SQL also supports reading and writing data stored in [Apache Hive](http://hive.apache.org/).
    
    However, since Hive has a large number of dependencies, these dependencies are not included in the
    default Spark distribution. If Hive dependencies can be found on the classpath, Spark will load them
    automatically. Note that these Hive dependencies must also be present on all of the worker nodes, as
    they will need access to the Hive serialization and deserialization libraries (SerDes) in order to
    access data stored in Hive.
    
    Configuration of Hive is done by placing your `hive-site.xml`, `core-site.xml` (for security configuration),
    
    and `hdfs-site.xml` (for HDFS configuration) file in `conf/`.
    
    When working with Hive, one must instantiate `SparkSession` with Hive support, including
    connectivity to a persistent Hive metastore, support for Hive serdes, and Hive user-defined functions.
    Users who do not have an existing Hive deployment can still enable Hive support. When not configured
    by the `hive-site.xml`, the context automatically creates `metastore_db` in the current directory and
    creates a directory configured by `spark.sql.warehouse.dir`, which defaults to the directory
    
    `spark-warehouse` in the current directory that the Spark application is started. Note that
    
    the `hive.metastore.warehouse.dir` property in `hive-site.xml` is deprecated since Spark 2.0.0.
    Instead, use `spark.sql.warehouse.dir` to specify the default location of database in warehouse.
    
    You may need to grant write privilege to the user who starts the Spark application.
    
    <div class="codetabs">
    
    <div data-lang="scala"  markdown="1">
    
    {% include_example spark_hive scala/org/apache/spark/examples/sql/hive/SparkHiveExample.scala %}
    
    </div>
    
    <div data-lang="java"  markdown="1">
    
    {% include_example spark_hive java/org/apache/spark/examples/sql/hive/JavaSparkHiveExample.java %}
    
    <div data-lang="python"  markdown="1">
    
    {% include_example spark_hive python/sql/hive.py %}
    
    When working with Hive one must instantiate `SparkSession` with Hive support. This
    
    adds support for finding tables in the MetaStore and writing queries using HiveQL.
    
    
    {% include_example spark_hive r/RSparkSQLExample.R %}
    
    ### Specifying storage format for Hive tables
    
    When you create a Hive table, you need to define how this table should read/write data from/to file system,
    i.e. the "input format" and "output format". You also need to define how this table should deserialize the data
    to rows, or serialize rows to data, i.e. the "serde". The following options can be used to specify the storage
    format("serde", "input format", "output format"), e.g. `CREATE TABLE src(id int) USING hive OPTIONS(fileFormat 'parquet')`.
    By default, we will read the table files as plain text. Note that, Hive storage handler is not supported yet when
    creating table, you can create a table using storage handler at Hive side, and use Spark SQL to read it.
    
    <table class="table">
      <tr><th>Property Name</th><th>Meaning</th></tr>
      <tr>
        <td><code>fileFormat</code></td>
        <td>
          A fileFormat is kind of a package of storage format specifications, including "serde", "input format" and
          "output format". Currently we support 6 fileFormats: 'sequencefile', 'rcfile', 'orc', 'parquet', 'textfile' and 'avro'.
        </td>
      </tr>
    
      <tr>
        <td><code>inputFormat, outputFormat</code></td>
        <td>
          These 2 options specify the name of a corresponding `InputFormat` and `OutputFormat` class as a string literal,
          e.g. `org.apache.hadoop.hive.ql.io.orc.OrcInputFormat`. These 2 options must be appeared in pair, and you can not
          specify them if you already specified the `fileFormat` option.
        </td>
      </tr>
    
      <tr>
        <td><code>serde</code></td>
        <td>
          This option specifies the name of a serde class. When the `fileFormat` option is specified, do not specify this option
          if the given `fileFormat` already include the information of serde. Currently "sequencefile", "textfile" and "rcfile"
          don't include the serde information and you can use this option with these 3 fileFormats.
        </td>
      </tr>
    
      <tr>
        <td><code>fieldDelim, escapeDelim, collectionDelim, mapkeyDelim, lineDelim</code></td>
        <td>
          These options can only be used with "textfile" fileFormat. They define how to read delimited files into rows.
        </td>
      </tr>
    </table>
    
    All other properties defined with `OPTIONS` will be regarded as Hive serde properties.
    
    
    ### Interacting with Different Versions of Hive Metastore
    
    One of the most important pieces of Spark SQL's Hive support is interaction with Hive metastore,
    
    which enables Spark SQL to access metadata of Hive tables. Starting from Spark 1.4.0, a single binary
    
    build of Spark SQL can be used to query different versions of Hive metastores, using the configuration described below.
    Note that independent of the version of Hive that is being used to talk to the metastore, internally Spark SQL
    will compile against Hive 1.2.1 and use those classes for internal execution (serdes, UDFs, UDAFs, etc).
    
    The following options can be used to configure the version of Hive that is used to retrieve metadata:
    
      <tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
    
      <tr>
        <td><code>spark.sql.hive.metastore.version</code></td>
    
          Version of the Hive metastore. Available
    
          options are <code>0.12.0</code> through <code>1.2.1</code>.
    
        </td>
      </tr>
      <tr>
        <td><code>spark.sql.hive.metastore.jars</code></td>
    
        <td><code>builtin</code></td>
    
          Location of the jars that should be used to instantiate the HiveMetastoreClient. This
    
          property can be one of three options:
          <ol>
            <li><code>builtin</code></li>
    
            Use Hive 1.2.1, which is bundled with the Spark assembly when <code>-Phive</code> is
    
            enabled. When this option is chosen, <code>spark.sql.hive.metastore.version</code> must be
    
            either <code>1.2.1</code> or not defined.
    
            Use Hive jars of specified version downloaded from Maven repositories. This configuration
    
            is not generally recommended for production deployments.
    
            <li>A classpath in the standard format for the JVM. This classpath must include all of Hive
            and its dependencies, including the correct version of Hadoop. These jars only need to be
    
            present on the driver, but if you are running in yarn cluster mode then you must ensure
    
            they are packaged with your application.</li>
    
          </ol>
        </td>
      </tr>
      <tr>
        <td><code>spark.sql.hive.metastore.sharedPrefixes</code></td>
    
        <td><code>com.mysql.jdbc,<br/>org.postgresql,<br/>com.microsoft.sqlserver,<br/>oracle.jdbc</code></td>
    
        <td>
          <p>
            A comma separated list of class prefixes that should be loaded using the classloader that is
            shared between Spark SQL and a specific version of Hive. An example of classes that should
            be shared is JDBC drivers that are needed to talk to the metastore. Other classes that need
    
            to be shared are those that interact with classes that are already shared. For example,
    
            custom appenders that are used by log4j.
          </p>
        </td>
      </tr>
      <tr>
        <td><code>spark.sql.hive.metastore.barrierPrefixes</code></td>
    
        <td><code>(empty)</code></td>
    
        <td>
          <p>
            A comma separated list of class prefixes that should explicitly be reloaded for each version
    
            of Hive that Spark SQL is communicating with. For example, Hive UDFs that are declared in a
    
            prefix that typically would be shared (i.e. <code>org.apache.spark.*</code>).
          </p>
        </td>
      </tr>
    </table>
    
    
    Spark SQL also includes a data source that can read data from other databases using JDBC. This
    
    functionality should be preferred over using [JdbcRDD](api/scala/index.html#org.apache.spark.rdd.JdbcRDD).
    This is because the results are returned
    as a DataFrame and they can easily be processed in Spark SQL or joined with other data sources.
    The JDBC data source is also easier to use from Java or Python as it does not require the user to
    provide a ClassTag.
    (Note that this is different than the Spark SQL JDBC server, which allows other applications to
    run queries using Spark SQL).
    
    To get started you will need to include the JDBC driver for you particular database on the
    
    spark classpath. For example, to connect to postgres from the Spark Shell you would run the
    
    bin/spark-shell --driver-class-path postgresql-9.4.1207.jar --jars postgresql-9.4.1207.jar
    
    Tables from the remote database can be loaded as a DataFrame or Spark SQL temporary view using
    
    the Data Sources API. Users can specify the JDBC connection properties in the data source options.
    <code>user</code> and <code>password</code> are normally provided as connection properties for
    logging into the data sources. In addition to the connection properties, Spark also supports
    
    the following case-insensitive options:
    
    
    <table class="table">
      <tr><th>Property Name</th><th>Meaning</th></tr>
      <tr>
        <td><code>url</code></td>
        <td>
    
          The JDBC URL to connect to. The source-specific connection properties may be specified in the URL. e.g., <code>jdbc:postgresql://localhost/test?user=fred&password=secret</code>
    
          The JDBC table that should be read. Note that anything that is valid in a <code>FROM</code> clause of
          a SQL query can be used. For example, instead of a full table you could also use a
    
          subquery in parentheses.
        </td>
      </tr>
    
      <tr>
        <td><code>driver</code></td>
        <td>
    
          The class name of the JDBC driver to use to connect to this URL.
    
        <td><code>partitionColumn, lowerBound, upperBound</code></td>
    
          These options must all be specified if any of them is specified. In addition,
          <code>numPartitions</code> must be specified. They describe how to partition the table when
          reading in parallel from multiple workers.
    
          <code>partitionColumn</code> must be a numeric column from the table in question. Notice
          that <code>lowerBound</code> and <code>upperBound</code> are just used to decide the
          partition stride, not for filtering the rows in table. So all rows in the table will be
    
          partitioned and returned. This option applies only to reading.
    
      <tr>
         <td><code>numPartitions</code></td>
         <td>
           The maximum number of partitions that can be used for parallelism in table reading and
           writing. This also determines the maximum number of concurrent JDBC connections.
           If the number of partitions to write exceeds this limit, we decrease it to this limit by
           calling <code>coalesce(numPartitions)</code> before writing.
         </td>
      </tr>
    
    
        <td><code>fetchsize</code></td>
    
          The JDBC fetch size, which determines how many rows to fetch per round trip. This can help performance on JDBC drivers which default to low fetch size (eg. Oracle with 10 rows). This option applies only to reading.
    
      <tr>
         <td><code>batchsize</code></td>
         <td>
           The JDBC batch size, which determines how many rows to insert per round trip. This can help performance on JDBC drivers. This option applies only to writing. It defaults to <code>1000</code>.
         </td>
      </tr>
    
      <tr>
         <td><code>isolationLevel</code></td>
         <td>
    
           The transaction isolation level, which applies to current connection. It can be one of <code>NONE</code>, <code>READ_COMMITTED</code>, <code>READ_UNCOMMITTED</code>, <code>REPEATABLE_READ</code>, or <code>SERIALIZABLE</code>, corresponding to standard transaction isolation levels defined by JDBC's Connection object, with default of <code>READ_UNCOMMITTED</code>. This option applies only to writing. Please refer the documentation in <code>java.sql.Connection</code>.
    
      <tr>
         <td><code>sessionInitStatement</code></td>
         <td>
           After each database session is opened to the remote DB and before starting to read data, this option executes a custom SQL statement (or a PL/SQL block). Use this to implement session initialization code. Example: <code>option("sessionInitStatement", """BEGIN execute immediate 'alter session set "_serial_direct_read"=true'; END;""")</code>
         </td>
      </tr>
    
    
      <tr>
        <td><code>truncate</code></td>
        <td>
    
         This is a JDBC writer related option. When <code>SaveMode.Overwrite</code> is enabled, this option causes Spark to truncate an existing table instead of dropping and recreating it. This can be more efficient, and prevents the table metadata (e.g., indices) from being removed. However, it will not work in some cases, such as when the new data has a different schema. It defaults to <code>false</code>. This option applies only to writing.
    
      <tr>
        <td><code>createTableOptions</code></td>
        <td>
    
         This is a JDBC writer related option. If specified, this option allows setting of database-specific table and partition options when creating a table (e.g., <code>CREATE TABLE t (name string) ENGINE=InnoDB.</code>). This option applies only to writing.
    
      <tr>
        <td><code>createTableColumnTypes</code></td>
        <td>
         The database column data types to use instead of the defaults, when creating the table. Data type information should be specified in the same format as CREATE TABLE columns syntax (e.g: <code>"name CHAR(64), comments VARCHAR(1024)")</code>. The specified types should be valid spark sql data types. This option applies only to writing.
        </td>
    
      </tr>
    
      <tr>
        <td><code>customSchema</code></td>
        <td>
    
         The custom schema to use for reading data from JDBC connectors. For example, <code>"id DECIMAL(38, 0), name STRING"</code>. You can also specify partial fields, and the others use the default type mapping. For example, <code>"id DECIMAL(38, 0)"</code>. The column names should be identical to the corresponding column names of JDBC table. Users can specify the corresponding data types of Spark SQL instead of using the defaults. This option applies only to reading.
    
    </table>
    
    <div class="codetabs">
    
    <div data-lang="scala"  markdown="1">
    
    {% include_example jdbc_dataset scala/org/apache/spark/examples/sql/SQLDataSourceExample.scala %}
    
    </div>
    
    <div data-lang="java"  markdown="1">
    
    {% include_example jdbc_dataset java/org/apache/spark/examples/sql/JavaSQLDataSourceExample.java %}
    
    </div>
    
    <div data-lang="python"  markdown="1">
    
    {% include_example jdbc_dataset python/sql/datasource.py %}
    
    {% include_example jdbc_dataset r/RSparkSQLExample.R %}
    
    <div data-lang="sql"  markdown="1">
    
    {% highlight sql %}
    
    
    USING org.apache.spark.sql.jdbc
    OPTIONS (
      url "jdbc:postgresql:dbserver",
    
      dbtable "schema.tablename",
    
      user 'username',
    
    INSERT INTO TABLE jdbcTable
    
    {% endhighlight %}
    
    </div>
    </div>
    
    ## Troubleshooting
    
     * The JDBC driver class must be visible to the primordial class loader on the client session and on all executors. This is because Java's DriverManager class does a security check that results in it ignoring all drivers not visible to the primordial class loader when one goes to open a connection. One convenient way to do this is to modify compute_classpath.sh on all worker nodes to include your driver JARs.
     * Some databases, such as H2, convert all names to upper case. You'll need to use upper case to refer to those names in Spark SQL.
    
    
    
    # Performance Tuning
    
    For some workloads it is possible to improve performance by either caching data in memory, or by
    turning on some experimental options.
    
    ## Caching Data In Memory
    
    Spark SQL can cache tables using an in-memory columnar format by calling `spark.catalog.cacheTable("tableName")` or `dataFrame.cache()`.
    
    Then Spark SQL will scan only required columns and will automatically tune compression to minimize
    
    memory usage and GC pressure. You can call `spark.catalog.uncacheTable("tableName")` to remove the table from memory.
    
    Configuration of in-memory caching can be done using the `setConf` method on `SparkSession` or by running
    
    `SET key=value` commands using SQL.
    
    <table class="table">
    <tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
    <tr>
      <td><code>spark.sql.inMemoryColumnarStorage.compressed</code></td>
    
      <td>true</td>
    
      <td>
        When set to true Spark SQL will automatically select a compression codec for each column based
        on statistics of the data.
      </td>
    </tr>
    <tr>
      <td><code>spark.sql.inMemoryColumnarStorage.batchSize</code></td>
    
      <td>10000</td>
    
        Controls the size of batches for columnar caching. Larger batch sizes can improve memory utilization
    
        and compression, but risk OOMs when caching data.
      </td>
    </tr>
    
    </table>
    
    
    ## Other Configuration Options
    
    The following options can also be used to tune the performance of query execution. It is possible
    
    that these options will be deprecated in future release as more optimizations are performed automatically.
    
    <table class="table">
      <tr><th>Property Name</th><th>Default</th><th>Meaning</th></tr>
    
      <tr>
        <td><code>spark.sql.files.maxPartitionBytes</code></td>
        <td>134217728 (128 MB)</td>
        <td>
          The maximum number of bytes to pack into a single partition when reading files.
        </td>
      </tr>
      <tr>
        <td><code>spark.sql.files.openCostInBytes</code></td>
        <td>4194304 (4 MB)</td>
        <td>
          The estimated cost to open a file, measured by the number of bytes could be scanned in the same
          time. This is used when putting multiple files into a partition. It is better to over estimated,
          then the partitions with small files will be faster than partitions with bigger files (which is
          scheduled first).
        </td>
      </tr>
    
      <tr>
        <td><code>spark.sql.broadcastTimeout</code></td>
        <td>300</td>
        <td>
        <p>
          Timeout in seconds for the broadcast wait time in broadcast joins
        </p>
        </td>
      </tr>
    
      <tr>
        <td><code>spark.sql.autoBroadcastJoinThreshold</code></td>
    
        <td>10485760 (10 MB)</td>
    
        <td>
          Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when
    
          performing a join. By setting this value to -1 broadcasting can be disabled. Note that currently
    
          statistics are only supported for Hive Metastore tables where the command
    
          <code>ANALYZE TABLE &lt;tableName&gt; COMPUTE STATISTICS noscan</code> has been run.
    
        </td>
      </tr>
      <tr>
        <td><code>spark.sql.shuffle.partitions</code></td>
        <td>200</td>
        <td>
          Configures the number of partitions to use when shuffling data for joins or aggregations.
        </td>
      </tr>
    </table>
    
    
    Spark SQL can also act as a distributed query engine using its JDBC/ODBC or command-line interface.
    In this mode, end-users or applications can interact with Spark SQL directly to run SQL queries,
    without the need to write any code.
    
    ## Running the Thrift JDBC/ODBC server
    
    The Thrift JDBC/ODBC server implemented here corresponds to the [`HiveServer2`](https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2)
    
    in Hive 1.2.1 You can test the JDBC server with the beeline script that comes with either Spark or Hive 1.2.1.
    
    To start the JDBC/ODBC server, run the following in the Spark directory:
    
    This script accepts all `bin/spark-submit` command line options, plus a `--hiveconf` option to
    
    specify Hive properties. You may run `./sbin/start-thriftserver.sh --help` for a complete list of
    all available options. By default, the server listens on localhost:10000. You may override this
    
    behaviour via either environment variables, i.e.:
    
    
    {% highlight bash %}
    export HIVE_SERVER2_THRIFT_PORT=<listening-port>
    export HIVE_SERVER2_THRIFT_BIND_HOST=<listening-host>
    ./sbin/start-thriftserver.sh \
      --master <master-uri> \
      ...
    {% endhighlight %}
    
    or system properties:
    
    {% highlight bash %}
    ./sbin/start-thriftserver.sh \
      --hiveconf hive.server2.thrift.port=<listening-port> \
      --hiveconf hive.server2.thrift.bind.host=<listening-host> \
      --master <master-uri>
      ...
    {% endhighlight %}
    
    
    Now you can use beeline to test the Thrift JDBC/ODBC server:
    
    Connect to the JDBC/ODBC server in beeline with:
    
    
        beeline> !connect jdbc:hive2://localhost:10000
    
    Beeline will ask you for a username and password. In non-secure mode, simply enter the username on
    your machine and a blank password. For secure mode, please follow the instructions given in the
    
    [beeline documentation](https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients).
    
    Configuration of Hive is done by placing your `hive-site.xml`, `core-site.xml` and `hdfs-site.xml` files in `conf/`.
    
    You may also use the beeline script that comes with Hive.
    
    Thrift JDBC server also supports sending thrift RPC messages over HTTP transport.
    Use the following setting to enable HTTP mode as system property or in `hive-site.xml` file in `conf/`:
    
        hive.server2.transport.mode - Set this to value: http
    
        hive.server2.thrift.http.port - HTTP port number to listen on; default is 10001
    
        hive.server2.http.endpoint - HTTP endpoint; default is cliservice
    
    To test, use beeline to connect to the JDBC/ODBC server in http mode with:
    
        beeline> !connect jdbc:hive2://<host>:<port>/<database>?hive.server2.transport.mode=http;hive.server2.thrift.http.path=<http_endpoint>
    
    
    
    ## Running the Spark SQL CLI
    
    The Spark SQL CLI is a convenient tool to run the Hive metastore service in local mode and execute
    
    queries input from the command line. Note that the Spark SQL CLI cannot talk to the Thrift JDBC server.
    
    
    To start the Spark SQL CLI, run the following in the Spark directory:
    
        ./bin/spark-sql
    
    
    Configuration of Hive is done by placing your `hive-site.xml`, `core-site.xml` and `hdfs-site.xml` files in `conf/`.
    
    You may run `./bin/spark-sql --help` for a complete list of all available
    options.
    
    
    ## Upgrading From Spark SQL 2.2 to 2.3
    
      - Since Spark 2.3, the queries from raw JSON/CSV files are disallowed when the referenced columns only include the internal corrupt record column (named `_corrupt_record` by default). For example, `spark.read.schema(schema).json(file).filter($"_corrupt_record".isNotNull).count()` and `spark.read.schema(schema).json(file).select("_corrupt_record").show()`. Instead, you can cache or save the parsed results and then send the same query. For example, `val df = spark.read.schema(schema).json(file).cache()` and then `df.filter($"_corrupt_record".isNotNull).count()`.
    
    
    ## Upgrading From Spark SQL 2.1 to 2.2
    
      - Spark 2.1.1 introduced a new configuration key: `spark.sql.hive.caseSensitiveInferenceMode`. It had a default setting of `NEVER_INFER`, which kept behavior identical to 2.1.0. However, Spark 2.2.0 changes this setting's default value to `INFER_AND_SAVE` to restore compatibility with reading Hive metastore tables whose underlying file schema have mixed-case column names. With the `INFER_AND_SAVE` configuration value, on first access Spark will perform schema inference on any Hive metastore table for which it has not already saved an inferred schema. Note that schema inference can be a very time consuming operation for tables with thousands of partitions. If compatibility with mixed-case column names is not a concern, you can safely set `spark.sql.hive.caseSensitiveInferenceMode` to `NEVER_INFER` to avoid the initial overhead of schema inference. Note that with the new default `INFER_AND_SAVE` setting, the results of the schema inference are saved as a metastore key for future use. Therefore, the initial schema inference occurs only at a table's first access.
    
    
    ## Upgrading From Spark SQL 2.0 to 2.1
    
     - Datasource tables now store partition metadata in the Hive metastore. This means that Hive DDLs such as `ALTER TABLE PARTITION ... SET LOCATION` are now available for tables created with the Datasource API.
        - Legacy datasource tables can be migrated to this format via the `MSCK REPAIR TABLE` command. Migrating legacy tables is recommended to take advantage of Hive DDL support and improved planning performance.
        - To determine if a table has been migrated, look for the `PartitionProvider: Catalog` attribute when issuing `DESCRIBE FORMATTED` on the table.
     - Changes to `INSERT OVERWRITE TABLE ... PARTITION ...` behavior for Datasource tables.
        - In prior Spark versions `INSERT OVERWRITE` overwrote the entire Datasource table, even when given a partition specification. Now only partitions matching the specification are overwritten.
        - Note that this still differs from the behavior of Hive tables, which is to overwrite only partitions overlapping with newly inserted data.
    
    
    ## Upgrading From Spark SQL 1.6 to 2.0
    
     - `SparkSession` is now the new entry point of Spark that replaces the old `SQLContext` and
    
       `HiveContext`. Note that the old SQLContext and HiveContext are kept for backward compatibility. A new `catalog` interface is accessible from `SparkSession` - existing API on databases and tables access such as `listTables`, `createExternalTable`, `dropTempView`, `cacheTable` are moved here.
    
    
     - Dataset API and DataFrame API are unified. In Scala, `DataFrame` becomes a type alias for
       `Dataset[Row]`, while Java API users must replace `DataFrame` with `Dataset<Row>`. Both the typed
    
       transformations (e.g., `map`, `filter`, and `groupByKey`) and untyped transformations (e.g.,
    
       `select` and `groupBy`) are available on the Dataset class. Since compile-time type-safety in
       Python and R is not a language feature, the concept of Dataset does not apply to these languages’
       APIs. Instead, `DataFrame` remains the primary programing abstraction, which is analogous to the
       single-node data frame notion in these languages.
    
    
     - Dataset and DataFrame API `unionAll` has been deprecated and replaced by `union`
     - Dataset and DataFrame API `explode` has been deprecated, alternatively, use `functions.explode()` with `select` or `flatMap`
     - Dataset and DataFrame API `registerTempTable` has been deprecated and replaced by `createOrReplaceTempView`
    
    
     - Changes to `CREATE TABLE ... LOCATION` behavior for Hive tables.
        - From Spark 2.0, `CREATE TABLE ... LOCATION` is equivalent to `CREATE EXTERNAL TABLE ... LOCATION`
          in order to prevent accidental dropping the existing data in the user-provided locations.
          That means, a Hive table created in Spark SQL with the user-specified location is always a Hive external table.
          Dropping external tables will not remove the data. Users are not allowed to specify the location for Hive managed tables.
          Note that this is different from the Hive behavior.
        - As a result, `DROP TABLE` statements on those tables will not remove the data.
    
    
     - `spark.sql.parquet.cacheMetadata` is no longer used.
       See [SPARK-13664](https://issues.apache.org/jira/browse/SPARK-13664) for details.
    
    
     - From Spark 1.6, by default the Thrift server runs in multi-session mode. Which means each JDBC/ODBC
       connection owns a copy of their own SQL configuration and temporary function registry. Cached
       tables are still shared though. If you prefer to run the Thrift server in the old single-session
       mode, please set option `spark.sql.hive.thriftServer.singleSession` to `true`. You may either add
    
       this option to `spark-defaults.conf`, or pass it to `start-thriftserver.sh` via `--conf`:
    
       {% highlight bash %}
       ./sbin/start-thriftserver.sh \
         --conf spark.sql.hive.thriftServer.singleSession=true \
         ...
       {% endhighlight %}
    
     - Since 1.6.1, withColumn method in sparkR supports adding a new column to or replacing existing columns
       of the same name of a DataFrame.
    
     - From Spark 1.6, LongType casts to TimestampType expect seconds instead of microseconds. This
       change was made to match the behavior of Hive 1.2 for more consistent type casting to TimestampType
       from numeric types. See [SPARK-11724](https://issues.apache.org/jira/browse/SPARK-11724) for
       details.
    
    
    ## Upgrading From Spark SQL 1.4 to 1.5
    
     - Optimized execution using manually managed memory (Tungsten) is now enabled by default, along with
    
       code generation for expression evaluation. These features can both be disabled by setting
    
       `spark.sql.tungsten.enabled` to `false`.
    
     - Parquet schema merging is no longer enabled by default. It can be re-enabled by setting
    
       `spark.sql.parquet.mergeSchema` to `true`.
    
     - Resolution of strings to columns in python now supports using dots (`.`) to qualify the column or
    
       access nested values. For example `df['table.column.nestedField']`. However, this means that if
    
       your column name contains any dots you must now escape them using backticks (e.g., ``table.`column.with.dots`.nested``).
    
     - In-memory columnar storage partition pruning is on by default. It can be disabled by setting
       `spark.sql.inMemoryColumnarStorage.partitionPruning` to `false`.
     - Unlimited precision decimal columns are no longer supported, instead Spark SQL enforces a maximum
    
       precision of 38. When inferring schema from `BigDecimal` objects, a precision of (38, 18) is now
    
       used. When no precision is specified in DDL then the default remains `Decimal(10, 0)`.
     - Timestamps are now stored at a precision of 1us, rather than 1ns
    
     - In the `sql` dialect, floating point numbers are now parsed as decimal. HiveQL parsing remains
    
     - The canonical name of SQL/DataFrame functions are now lower case (e.g., sum vs SUM).
    
     - JSON data source will not automatically load new files that are created by other applications
       (i.e. files that are not inserted to the dataset through Spark SQL).
       For a JSON persistent table (i.e. the metadata of the table is stored in Hive Metastore),
       users can use `REFRESH TABLE` SQL command or `HiveContext`'s `refreshTable` method
       to include those new files to the table. For a DataFrame representing a JSON dataset, users need to recreate
       the DataFrame and the new DataFrame will include new files.
    
     - DataFrame.withColumn method in pySpark supports adding a new column or replacing existing columns of the same name.
    
    #### DataFrame data reader/writer interface
    
    Based on user feedback, we created a new, more fluid API for reading data in (`SQLContext.read`)
    
    and writing data out (`DataFrame.write`),
    
    and deprecated the old APIs (e.g., `SQLContext.parquetFile`, `SQLContext.jsonFile`).
    
    
    See the API docs for `SQLContext.read` (
      <a href="api/scala/index.html#org.apache.spark.sql.SQLContext@read:DataFrameReader">Scala</a>,
      <a href="api/java/org/apache/spark/sql/SQLContext.html#read()">Java</a>,
      <a href="api/python/pyspark.sql.html#pyspark.sql.SQLContext.read">Python</a>
    ) and `DataFrame.write` (
      <a href="api/scala/index.html#org.apache.spark.sql.DataFrame@write:DataFrameWriter">Scala</a>,
      <a href="api/java/org/apache/spark/sql/DataFrame.html#write()">Java</a>,
      <a href="api/python/pyspark.sql.html#pyspark.sql.DataFrame.write">Python</a>
    ) more information.
    
    
    #### DataFrame.groupBy retains grouping columns
    
    
    Based on user feedback, we changed the default behavior of `DataFrame.groupBy().agg()` to retain the
    grouping columns in the resulting `DataFrame`. To keep the behavior in 1.3, set `spark.sql.retainGroupColumns` to `false`.
    
    
    <div class="codetabs">
    <div data-lang="scala"  markdown="1">
    {% highlight scala %}
    
    // In 1.3.x, in order for the grouping column "department" to show up,
    // it must be included explicitly as part of the agg function call.
    df.groupBy("department").agg($"department", max("age"), sum("expense"))
    
    // In 1.4+, grouping column "department" is included automatically.
    df.groupBy("department").agg(max("age"), sum("expense"))
    
    // Revert to 1.3 behavior (not retaining grouping column) by:
    sqlContext.setConf("spark.sql.retainGroupColumns", "false")
    
    {% endhighlight %}
    </div>
    
    <div data-lang="java"  markdown="1">
    {% highlight java %}
    
    // In 1.3.x, in order for the grouping column "department" to show up,
    // it must be included explicitly as part of the agg function call.
    df.groupBy("department").agg(col("department"), max("age"), sum("expense"));
    
    // In 1.4+, grouping column "department" is included automatically.
    df.groupBy("department").agg(max("age"), sum("expense"));
    
    // Revert to 1.3 behavior (not retaining grouping column) by:
    sqlContext.setConf("spark.sql.retainGroupColumns", "false");
    
    {% endhighlight %}
    </div>
    
    <div data-lang="python"  markdown="1">
    {% highlight python %}
    
    import pyspark.sql.functions as func
    
    # In 1.3.x, in order for the grouping column "department" to show up,
    # it must be included explicitly as part of the agg function call.
    
    df.groupBy("department").agg(df["department"], func.max("age"), func.sum("expense"))
    
    
    # In 1.4+, grouping column "department" is included automatically.
    df.groupBy("department").agg(func.max("age"), func.sum("expense"))
    
    # Revert to 1.3.x behavior (not retaining grouping column) by:
    sqlContext.setConf("spark.sql.retainGroupColumns", "false")
    
    {% endhighlight %}
    </div>
    
    </div>
    
    
    
    #### Behavior change on DataFrame.withColumn
    
    Prior to 1.4, DataFrame.withColumn() supports adding a column only. The column will always be added
    as a new column with its specified name in the result DataFrame even if there may be any existing
    columns of the same name. Since 1.4, DataFrame.withColumn() supports adding a column of a different
    name from names of all existing columns or replacing existing columns of the same name.
    
    Note that this change is only for Scala API, not for PySpark and SparkR.
    
    
    
    ## Upgrading from Spark SQL 1.0-1.2 to 1.3
    
    In Spark 1.3 we removed the "Alpha" label from Spark SQL and as part of this did a cleanup of the
    
    available APIs. From Spark 1.3 onwards, Spark SQL will provide binary compatibility with other
    releases in the 1.X series. This compatibility guarantee excludes APIs that are explicitly marked
    
    as unstable (i.e., DeveloperAPI or Experimental).
    
    #### Rename of SchemaRDD to DataFrame
    
    The largest change that users will notice when upgrading to Spark SQL 1.3 is that `SchemaRDD` has
    
    been renamed to `DataFrame`. This is primarily because DataFrames no longer inherit from RDD
    
    directly, but instead provide most of the functionality that RDDs provide though their own
    
    implementation. DataFrames can still be converted to RDDs by calling the `.rdd` method.
    
    
    In Scala there is a type alias from `SchemaRDD` to `DataFrame` to provide source compatibility for
    
    some use cases. It is still recommended that users update their code to use `DataFrame` instead.
    
    Java and Python users will need to update their code.
    
    #### Unification of the Java and Scala APIs
    
    Prior to Spark 1.3 there were separate Java compatible classes (`JavaSQLContext` and `JavaSchemaRDD`)
    
    that mirrored the Scala API. In Spark 1.3 the Java API and Scala API have been unified. Users
    of either language should use `SQLContext` and `DataFrame`. In general theses classes try to
    
    use types that are usable from both languages (i.e. `Array` instead of language specific collections).
    In some cases where no common type exists (e.g., for passing in closures or Maps) function overloading
    is used instead.
    
    
    Additionally the Java specific types API has been removed. Users of both Scala and Java should
    
    use the classes present in `org.apache.spark.sql.types` to describe schema programmatically.
    
    
    #### Isolation of Implicit Conversions and Removal of dsl Package (Scala-only)
    
    Many of the code examples prior to Spark 1.3 started with `import sqlContext._`, which brought
    
    all of the functions from sqlContext into scope. In Spark 1.3 we have isolated the implicit
    
    conversions for converting `RDD`s into `DataFrame`s into an object inside of the `SQLContext`.
    Users should now write `import sqlContext.implicits._`.
    
    Additionally, the implicit conversions now only augment RDDs that are composed of `Product`s (i.e.,
    case classes or tuples) with a method `toDF`, instead of applying automatically.
    
    When using function inside of the DSL (now replaced with the `DataFrame` API) users used to import
    
    `org.apache.spark.sql.catalyst.dsl`. Instead the public dataframe functions API should be used:
    
    `import org.apache.spark.sql.functions._`.
    
    #### Removal of the type aliases in org.apache.spark.sql for DataType (Scala-only)
    
    Spark 1.3 removes the type aliases that were present in the base sql package for `DataType`. Users
    should instead import the classes in `org.apache.spark.sql.types`
    
    
    #### UDF Registration Moved to `sqlContext.udf` (Java & Scala)
    
    
    Functions that are used to register UDFs, either for use in the DataFrame DSL or SQL, have been
    moved into the udf object in `SQLContext`.
    
    <div class="codetabs">
    <div data-lang="scala"  markdown="1">
    
    sqlContext.udf.register("strLen", (s: String) => s.length())
    
    
    {% endhighlight %}
    </div>
    
    <div data-lang="java"  markdown="1">
    {% highlight java %}
    
    
    sqlContext.udf().register("strLen", (String s) -> s.length(), DataTypes.IntegerType);
    
    
    {% endhighlight %}
    </div>
    
    </div>
    
    Python UDF registration is unchanged.
    
    #### Python DataTypes No Longer Singletons
    
    When using DataTypes in Python you will need to construct them (i.e. `StringType()`) instead of
    referencing a singleton.
    
    
    ## Compatibility with Apache Hive
    
    
    Spark SQL is designed to be compatible with the Hive Metastore, SerDes and UDFs.
    Currently Hive SerDes and UDFs are based on Hive 1.2.1,
    and Spark SQL can be connected to different versions of Hive Metastore
    
    (from 0.12.0 to 2.1.1. Also see [Interacting with Different Versions of Hive Metastore] (#interacting-with-different-versions-of-hive-metastore)).
    
    #### Deploying in Existing Hive Warehouses
    
    The Spark SQL Thrift JDBC server is designed to be "out of the box" compatible with existing Hive
    
    installations. You do not need to modify your existing Hive Metastore or change the data placement
    or partitioning of your tables.
    
    
    ### Supported Hive Features
    
    
    Spark SQL supports the vast majority of Hive features, such as:
    
    * Hive query statements, including:
    
      * `SELECT`
      * `GROUP BY`
      * `ORDER BY`
      * `CLUSTER BY`
      * `SORT BY`
    
      * Relational operators (`=`, `⇔`, `==`, `<>`, `<`, `>`, `>=`, `<=`, etc)
      * Arithmetic operators (`+`, `-`, `*`, `/`, `%`, etc)
      * Logical operators (`AND`, `&&`, `OR`, `||`, etc)
      * Complex type constructors
      * Mathematical functions (`sign`, `ln`, `cos`, etc)
      * String functions (`instr`, `length`, `printf`, etc)
    
    * User defined functions (UDF)
    * User defined aggregation functions (UDAF)
    
    * User defined serialization formats (SerDes)
    
      * `JOIN`
      * `{LEFT|RIGHT|FULL} OUTER JOIN`
      * `LEFT SEMI JOIN`
      * `CROSS JOIN`
    
    * Sub-queries
      * `SELECT col FROM ( SELECT a + b AS col from t1) t2`
    
    * Partitioned tables including dynamic partition insertion
    
    * All Hive DDL Functions, including:
    
      * `CREATE TABLE`
      * `CREATE TABLE AS SELECT`
      * `ALTER TABLE`
    
      * `TINYINT`
      * `SMALLINT`
      * `INT`
      * `BIGINT`
      * `BOOLEAN`
      * `FLOAT`
      * `DOUBLE`
      * `STRING`
      * `BINARY`
      * `TIMESTAMP`
    
      * `ARRAY<>`
      * `MAP<>`
      * `STRUCT<>`
    
    ### Unsupported Hive Functionality
    
    
    Below is a list of Hive features that we don't support yet. Most of these features are rarely used
    in Hive deployments.
    
    **Major Hive Features**
    
    * Tables with buckets: bucket is the hash partitioning within a Hive table partition. Spark SQL
      doesn't support buckets yet.
    
    
    
    * `UNION` type
    
    * Unique join
    * Column statistics collecting: Spark SQL does not piggyback scans to collect column statistics at
    
      the moment and only supports populating the sizeInBytes field of the hive metastore.
    
    
    **Hive Input/Output Formats**
    
    * File format for CLI: For results showing back to the CLI, Spark SQL only supports TextOutputFormat.
    * Hadoop archive
    
    **Hive Optimizations**
    
    A handful of Hive optimizations are not yet included in Spark. Some of these (such as indexes) are
    
    less important due to Spark SQL's in-memory computational model. Others are slotted for future
    
    releases of Spark SQL.
    
    * Block level bitmap indexes and virtual columns (used to build indexes)
    * Automatically determine the number of reducers for joins and groupbys: Currently in Spark SQL, you
    
      need to control the degree of parallelism post-shuffle using "`SET spark.sql.shuffle.partitions=[num_tasks];`".
    
    * Meta-data only query: For queries that can be answered by using only meta data, Spark SQL still
      launches tasks to compute the result.
    * Skew data flag: Spark SQL does not follow the skew data flags in Hive.
    * `STREAMTABLE` hint in join: Spark SQL does not follow the `STREAMTABLE` hint.
    * Merge multiple small files for query results: if the result output contains multiple small files,
      Hive can optionally merge the small files into fewer large files to avoid overflowing the HDFS
      metadata. Spark SQL does not support that.
    
    
    **Hive UDF/UDTF/UDAF**
    
    Not all the APIs of the Hive UDF/UDTF/UDAF are supported by Spark SQL. Below are the unsupported APIs:
    
    * `getRequiredJars` and `getRequiredFiles` (`UDF` and `GenericUDF`) are functions to automatically
      include additional resources required by this UDF.
    * `initialize(StructObjectInspector)` in `GenericUDTF` is not supported yet. Spark SQL currently uses
      a deprecated interface `initialize(ObjectInspector[])` only.
    * `configure` (`GenericUDF`, `GenericUDTF`, and `GenericUDAFEvaluator`) is a function to initialize
      functions with `MapredContext`, which is inapplicable to Spark.
    * `close` (`GenericUDF` and `GenericUDAFEvaluator`) is a function to release associated resources.
      Spark SQL does not call this function when tasks finish.
    * `reset` (`GenericUDAFEvaluator`) is a function to re-initialize aggregation for reusing the same aggregation.
      Spark SQL currently does not support the reuse of aggregation.
    * `getWindowingEvaluator` (`GenericUDAFEvaluator`) is a function to optimize aggregation by evaluating
      an aggregate over a fixed window.
    
    
    Spark SQL and DataFrames support the following data types:
    
    
    * Numeric types
        - `ByteType`: Represents 1-byte signed integer numbers.
        The range of numbers is from `-128` to `127`.
        - `ShortType`: Represents 2-byte signed integer numbers.
        The range of numbers is from `-32768` to `32767`.
        - `IntegerType`: Represents 4-byte signed integer numbers.
        The range of numbers is from `-2147483648` to `2147483647`.
        - `LongType`: Represents 8-byte signed integer numbers.
        The range of numbers is from `-9223372036854775808` to `9223372036854775807`.
        - `FloatType`: Represents 4-byte single-precision floating point numbers.
        - `DoubleType`: Represents 8-byte double-precision floating point numbers.
    
        - `DecimalType`: Represents arbitrary-precision signed decimal numbers. Backed internally by `java.math.BigDecimal`. A `BigDecimal` consists of an arbitrary precision integer unscaled value and a 32-bit integer scale.
    
    * String type
        - `StringType`: Represents character string values.
    * Binary type
        - `BinaryType`: Represents byte sequence values.
    * Boolean type
        - `BooleanType`: Represents boolean values.
    * Datetime type
        - `TimestampType`: Represents values comprising values of fields year, month, day,
        hour, minute, and second.
    
        - `DateType`: Represents values comprising values of fields year, month, day.
    
    * Complex types
        - `ArrayType(elementType, containsNull)`: Represents values comprising a sequence of
        elements with the type of `elementType`. `containsNull` is used to indicate if
        elements in a `ArrayType` value can have `null` values.
        - `MapType(keyType, valueType, valueContainsNull)`:
        Represents values comprising a set of key-value pairs. The data type of keys are
        described by `keyType` and the data type of values are described by `valueType`.
        For a `MapType` value, keys are not allowed to have `null` values. `valueContainsNull`
        is used to indicate if values of a `MapType` value can have `null` values.
        - `StructType(fields)`: Represents values with the structure described by
        a sequence of `StructField`s (`fields`).
            * `StructField(name, dataType, nullable)`: Represents a field in a `StructType`.
            The name of a field is indicated by `name`. The data type of a field is indicated
            by `dataType`. `nullable` is used to indicate if values of this fields can have
            `null` values.
    
    <div class="codetabs">
    <div data-lang="scala"  markdown="1">
    
    
    All data types of Spark SQL are located in the package `org.apache.spark.sql.types`.
    
    You can access them by doing
    
    
    {% include_example data_types scala/org/apache/spark/examples/sql/SparkSQLExample.scala %}
    
    
    <table class="table">
    <tr>
      <th style="width:20%">Data type</th>
      <th style="width:40%">Value type in Scala</th>
      <th>API to access or create a data type</th></tr>
    <tr>
      <td> <b>ByteType</b> </td>
      <td> Byte </td>
      <td>
      ByteType
      </td>