Impala Tutorials

This section includes tutorial scenarios that demonstrate how to begin using Impala once the software is installed. It focuses on techniques for loading data, because once you have some data in tables and can query that data, you can quickly progress to more advanced Impala features.

Note:

Where practical, the tutorials take you from “ground zero” to having the desired Impala tables and data. In some cases, you might need to download additional files from outside sources, set up additional software components, modify commands or scripts to fit your own configuration, or substitute your own sample data.

Before trying these tutorial lessons, install Impala using one of these procedures:

  • If you already have some Apache Hadoop environment set up and just need to add Impala to it, follow the installation process described in Installing Impala. Make sure to also install the Hive metastore service if you do not already have Hive configured.

Tutorials for Getting Started

These tutorials demonstrate the basics of using Impala. They are intended for first-time users, and for trying out Impala on any new cluster to make sure the major components are working correctly.

Explore a New Impala Instance

This tutorial demonstrates techniques for finding your way around the tables and databases of an unfamiliar (possibly empty) Impala instance.

When you connect to an Impala instance for the first time, you use the SHOW DATABASES and SHOW TABLES statements to view the most common types of objects. Also, call the version() function to confirm which version of Impala you are running; the version number is important when consulting documentation and dealing with support issues.

A completely empty Impala instance contains no tables, but still has two databases:

  • default, where new tables are created when you do not specify any other database.
  • _impala_builtins, a system database used to hold all the built-in functions.

The following example shows how to see the available databases, and the tables in each. If the list of databases or tables is long, you can use wildcard notation to locate specific databases or tables based on their names.

  1. $ impala-shell -i localhost --quiet
  2. Starting Impala Shell without Kerberos authentication
  3. Welcome to the Impala shell. Press TAB twice to see a list of available commands.
  4. ...
  5. (Shell
  6. build version: Impala Shell v3.0.x (hash) built on
  7. date)
  8. [localhost:21000] > select version();
  9. +-------------------------------------------
  10. | version()
  11. +-------------------------------------------
  12. | impalad version ...
  13. | Built on ...
  14. +-------------------------------------------
  15. [localhost:21000] > show databases;
  16. +--------------------------+
  17. | name |
  18. +--------------------------+
  19. | _impala_builtins |
  20. | ctas |
  21. | d1 |
  22. | d2 |
  23. | d3 |
  24. | default |
  25. | explain_plans |
  26. | external_table |
  27. | file_formats |
  28. | tpc |
  29. +--------------------------+
  30. [localhost:21000] > select current_database();
  31. +--------------------+
  32. | current_database() |
  33. +--------------------+
  34. | default |
  35. +--------------------+
  36. [localhost:21000] > show tables;
  37. +-------+
  38. | name |
  39. +-------+
  40. | ex_t |
  41. | t1 |
  42. +-------+
  43. [localhost:21000] > show tables in d3;
  44. [localhost:21000] > show tables in tpc;
  45. +------------------------+
  46. | name |
  47. +------------------------+
  48. | city |
  49. | customer |
  50. | customer_address |
  51. | customer_demographics |
  52. | household_demographics |
  53. | item |
  54. | promotion |
  55. | store |
  56. | store2 |
  57. | store_sales |
  58. | ticket_view |
  59. | time_dim |
  60. | tpc_tables |
  61. +------------------------+
  62. [localhost:21000] > show tables in tpc like 'customer*';
  63. +-----------------------+
  64. | name |
  65. +-----------------------+
  66. | customer |
  67. | customer_address |
  68. | customer_demographics |
  69. +-----------------------+

Once you know what tables and databases are available, you descend into a database with the USE statement. To understand the structure of each table, you use the DESCRIBE command. Once inside a database, you can issue statements such as INSERT and SELECT that operate on particular tables.

The following example explores a database named TPC whose name we learned in the previous example. It shows how to filter the table names within a database based on a search string, examine the columns of a table, and run queries to examine the characteristics of the table data. For example, for an unfamiliar table you might want to know the number of rows, the number of different values for a column, and other properties such as whether the column contains any NULL values. When sampling the actual data values from a table, use a LIMIT clause to avoid excessive output if the table contains more rows or distinct values than you expect.

  1. [localhost:21000] > use tpc;
  2. [localhost:21000] > show tables like '*view*';
  3. +-------------+
  4. | name |
  5. +-------------+
  6. | ticket_view |
  7. +-------------+
  8. [localhost:21000] > describe city;
  9. +-------------+--------+---------+
  10. | name | type | comment |
  11. +-------------+--------+---------+
  12. | id | int | |
  13. | name | string | |
  14. | countrycode | string | |
  15. | district | string | |
  16. | population | int | |
  17. +-------------+--------+---------+
  18. [localhost:21000] > select count(*) from city;
  19. +----------+
  20. | count(*) |
  21. +----------+
  22. | 0 |
  23. +----------+
  24. [localhost:21000] > desc customer;
  25. +------------------------+--------+---------+
  26. | name | type | comment |
  27. +------------------------+--------+---------+
  28. | c_customer_sk | int | |
  29. | c_customer_id | string | |
  30. | c_current_cdemo_sk | int | |
  31. | c_current_hdemo_sk | int | |
  32. | c_current_addr_sk | int | |
  33. | c_first_shipto_date_sk | int | |
  34. | c_first_sales_date_sk | int | |
  35. | c_salutation | string | |
  36. | c_first_name | string | |
  37. | c_last_name | string | |
  38. | c_preferred_cust_flag | string | |
  39. | c_birth_day | int | |
  40. | c_birth_month | int | |
  41. | c_birth_year | int | |
  42. | c_birth_country | string | |
  43. | c_login | string | |
  44. | c_email_address | string | |
  45. | c_last_review_date | string | |
  46. +------------------------+--------+---------+
  47. [localhost:21000] > select count(*) from customer;
  48. +----------+
  49. | count(*) |
  50. +----------+
  51. | 100000 |
  52. +----------+
  53. [localhost:21000] > select count(distinct c_birth_month) from customer;
  54. +-------------------------------+
  55. | count(distinct c_birth_month) |
  56. +-------------------------------+
  57. | 12 |
  58. +-------------------------------+
  59. [localhost:21000] > select count(*) from customer where c_email_address is null;
  60. +----------+
  61. | count(*) |
  62. +----------+
  63. | 0 |
  64. +----------+
  65. [localhost:21000] > select distinct c_salutation from customer limit 10;
  66. +--------------+
  67. | c_salutation |
  68. +--------------+
  69. | Mr. |
  70. | Ms. |
  71. | Dr. |
  72. | |
  73. | Miss |
  74. | Sir |
  75. | Mrs. |
  76. +--------------+

When you graduate from read-only exploration, you use statements such as CREATE DATABASE and CREATE TABLE to set up your own database objects.

The following example demonstrates creating a new database holding a new table. Although the last example ended inside the TPC database, the new EXPERIMENTS database is not nested inside TPC; all databases are arranged in a single top-level list.

  1. [localhost:21000] > create database experiments;
  2. [localhost:21000] > show databases;
  3. +--------------------------+
  4. | name |
  5. +--------------------------+
  6. | _impala_builtins |
  7. | ctas |
  8. | d1 |
  9. | d2 |
  10. | d3 |
  11. | default |
  12. | experiments |
  13. | explain_plans |
  14. | external_table |
  15. | file_formats |
  16. | tpc |
  17. +--------------------------+
  18. [localhost:21000] > show databases like 'exp*';
  19. +---------------+
  20. | name |
  21. +---------------+
  22. | experiments |
  23. | explain_plans |
  24. +---------------+

The following example creates a new table, T1. To illustrate a common mistake, it creates this table inside the wrong database, the TPC database where the previous example ended. The ALTER TABLE statement lets you move the table to the intended database, EXPERIMENTS, as part of a rename operation. The USE statement is always needed to switch to a new database, and the current_database() function confirms which database the session is in, to avoid these kinds of mistakes.

  1. [localhost:21000] > create table t1 (x int);
  2. [localhost:21000] > show tables;
  3. +------------------------+
  4. | name |
  5. +------------------------+
  6. | city |
  7. | customer |
  8. | customer_address |
  9. | customer_demographics |
  10. | household_demographics |
  11. | item |
  12. | promotion |
  13. | store |
  14. | store2 |
  15. | store_sales |
  16. | t1 |
  17. | ticket_view |
  18. | time_dim |
  19. | tpc_tables |
  20. +------------------------+
  21. [localhost:21000] > select current_database();
  22. +--------------------+
  23. | current_database() |
  24. +--------------------+
  25. | tpc |
  26. +--------------------+
  27. [localhost:21000] > alter table t1 rename to experiments.t1;
  28. [localhost:21000] > use experiments;
  29. [localhost:21000] > show tables;
  30. +------+
  31. | name |
  32. +------+
  33. | t1 |
  34. +------+
  35. [localhost:21000] > select current_database();
  36. +--------------------+
  37. | current_database() |
  38. +--------------------+
  39. | experiments |
  40. +--------------------+

For your initial experiments with tables, you can use ones with just a few columns and a few rows, and text-format data files.

Note: As you graduate to more realistic scenarios, you will use more elaborate tables with many columns, features such as partitioning, and file formats such as Parquet. When dealing with realistic data volumes, you will bring in data using LOAD DATA or INSERT ... SELECT statements to operate on millions or billions of rows at once.

The following example sets up a couple of simple tables with a few rows, and performs queries involving sorting, aggregate functions and joins.

  1. [localhost:21000] > insert into t1 values (1), (3), (2), (4);
  2. [localhost:21000] > select x from t1 order by x desc;
  3. +---+
  4. | x |
  5. +---+
  6. | 4 |
  7. | 3 |
  8. | 2 |
  9. | 1 |
  10. +---+
  11. [localhost:21000] > select min(x), max(x), sum(x), avg(x) from t1;
  12. +--------+--------+--------+--------+
  13. | min(x) | max(x) | sum(x) | avg(x) |
  14. +--------+--------+--------+--------+
  15. | 1 | 4 | 10 | 2.5 |
  16. +--------+--------+--------+--------+
  17. [localhost:21000] > create table t2 (id int, word string);
  18. [localhost:21000] > insert into t2 values (1, "one"), (3, "three"), (5, 'five');
  19. [localhost:21000] > select word from t1 join t2 on (t1.x = t2.id);
  20. +-------+
  21. | word |
  22. +-------+
  23. | one |
  24. | three |
  25. +-------+

After completing this tutorial, you should now know:

  • How to tell which version of Impala is running on your system.
  • How to find the names of databases in an Impala instance, either displaying the full list or searching for specific names.
  • How to find the names of tables in an Impala database, either displaying the full list or searching for specific names.
  • How to switch between databases and check which database you are currently in.
  • How to learn the column names and types of a table.
  • How to create databases and tables, insert small amounts of test data, and run simple queries.

Load CSV Data from Local Files

This scenario illustrates how to create some very small tables, suitable for first-time users to experiment with Impala SQL features. TAB1 and TAB2 are loaded with data from files in HDFS. A subset of data is copied from TAB1 into TAB3.

Populate HDFS with the data you want to query. To begin this process, create one or more new subdirectories underneath your user directory in HDFS. The data for each table resides in a separate subdirectory. Substitute your own username for username where appropriate. This example uses the -p option with the mkdir operation to create any necessary parent directories if they do not already exist.

  1. $ whoami
  2. username
  3. $ hdfs dfs -ls /user
  4. Found 3 items
  5. drwxr-xr-x - username username 0 2013-04-22 18:54 /user/username
  6. drwxrwx--- - mapred mapred 0 2013-03-15 20:11 /user/history
  7. drwxr-xr-x - hue supergroup 0 2013-03-15 20:10 /user/hive
  8. $ hdfs dfs -mkdir -p /user/username/sample_data/tab1 /user/username/sample_data/tab2

Here is some sample data, for two tables named TAB1 and TAB2.

Copy the following content to .csv files in your local filesystem:

tab1.csv:

  1. 1,true,123.123,2012-10-24 08:55:00
  2. 2,false,1243.5,2012-10-25 13:40:00
  3. 3,false,24453.325,2008-08-22 09:33:21.123
  4. 4,false,243423.325,2007-05-12 22:32:21.33454
  5. 5,true,243.325,1953-04-22 09:11:33

tab2.csv:

  1. 1,true,12789.123
  2. 2,false,1243.5
  3. 3,false,24453.325
  4. 4,false,2423.3254
  5. 5,true,243.325
  6. 60,false,243565423.325
  7. 70,true,243.325
  8. 80,false,243423.325
  9. 90,true,243.325

Put each .csv file into a separate HDFS directory using commands like the following, which use paths available in the Impala Demo VM:

  1. $ hdfs dfs -put tab1.csv /user/username/sample_data/tab1
  2. $ hdfs dfs -ls /user/username/sample_data/tab1
  3. Found 1 items
  4. -rw-r--r-- 1 username username 192 2013-04-02 20:08 /user/username/sample_data/tab1/tab1.csv
  5. $ hdfs dfs -put tab2.csv /user/username/sample_data/tab2
  6. $ hdfs dfs -ls /user/username/sample_data/tab2
  7. Found 1 items
  8. -rw-r--r-- 1 username username 158 2013-04-02 20:09 /user/username/sample_data/tab2/tab2.csv

The name of each data file is not significant. In fact, when Impala examines the contents of the data directory for the first time, it considers all files in the directory to make up the data of the table, regardless of how many files there are or what the files are named.

To understand what paths are available within your own HDFS filesystem and what the permissions are for the various directories and files, issue hdfs dfs -ls / and work your way down the tree doing -ls operations for the various directories.

Use the impala-shell command to create tables, either interactively or through a SQL script.

The following example shows creating three tables. For each table, the example shows creating columns with various attributes such as Boolean or integer types. The example also includes commands that provide information about how the data is formatted, such as rows terminating with commas, which makes sense in the case of importing data from a .csv file. Where we already have .csv files containing data in the HDFS directory tree, we specify the location of the directory containing the appropriate .csv file. Impala considers all the data from all the files in that directory to represent the data for the table.

  1. DROP TABLE IF EXISTS tab1;
  2. -- The EXTERNAL clause means the data is located outside the central location
  3. -- for Impala data files and is preserved when the associated Impala table is dropped.
  4. -- We expect the data to already exist in the directory specified by the LOCATION clause.
  5. CREATE EXTERNAL TABLE tab1
  6. (
  7. id INT,
  8. col_1 BOOLEAN,
  9. col_2 DOUBLE,
  10. col_3 TIMESTAMP
  11. )
  12. ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
  13. LOCATION '/user/username/sample_data/tab1';
  14. DROP TABLE IF EXISTS tab2;
  15. -- TAB2 is an external table, similar to TAB1.
  16. CREATE EXTERNAL TABLE tab2
  17. (
  18. id INT,
  19. col_1 BOOLEAN,
  20. col_2 DOUBLE
  21. )
  22. ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
  23. LOCATION '/user/username/sample_data/tab2';
  24. DROP TABLE IF EXISTS tab3;
  25. -- Leaving out the EXTERNAL clause means the data will be managed
  26. -- in the central Impala data directory tree. Rather than reading
  27. -- existing data files when the table is created, we load the
  28. -- data after creating the table.
  29. CREATE TABLE tab3
  30. (
  31. id INT,
  32. col_1 BOOLEAN,
  33. col_2 DOUBLE,
  34. month INT,
  35. day INT
  36. )
  37. ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';

Note: Getting through these CREATE TABLE statements successfully is an important validation step to confirm everything is configured correctly with the Hive metastore and HDFS permissions. If you receive any errors during the CREATE TABLE statements:

  • Make sure you followed the installation instructions closely, in Installing Impala.
  • Make sure the hive.metastore.warehouse.dir property points to a directory that Impala can write to. The ownership should be hive:hive, and the impala user should also be a member of the hive group.

Point an Impala Table at Existing Data Files

A convenient way to set up data for Impala to access is to use an external table, where the data already exists in a set of HDFS files and you just point the Impala table at the directory containing those files. For example, you might run in impala-shell a *.sql file with contents similar to the following, to create an Impala table that accesses an existing data file used by Hive.

The following examples set up 2 tables, referencing the paths and sample data from the sample TPC-DS kit for Impala. For historical reasons, the data physically resides in an HDFS directory tree under /user/hive, although this particular data is entirely managed by Impala rather than Hive. When we create an external table, we specify the directory containing one or more data files, and Impala queries the combined content of all the files inside that directory. Here is how we examine the directories and files within the HDFS filesystem:

  1. $ cd ~/username/datasets
  2. $ ./tpcds-setup.sh
  3. ... Downloads and unzips the kit, builds the data and loads it into HDFS ...
  4. $ hdfs dfs -ls /user/hive/tpcds/customer
  5. Found 1 items
  6. -rw-r--r-- 1 username supergroup 13209372 2013-03-22 18:09 /user/hive/tpcds/customer/customer.dat
  7. $ hdfs dfs -cat /user/hive/tpcds/customer/customer.dat | more
  8. 1|AAAAAAAABAAAAAAA|980124|7135|32946|2452238|2452208|Mr.|Javier|Lewis|Y|9|12|1936|CHILE||Javie
  9. r.Lewis@VFAxlnZEvOx.org|2452508|
  10. 2|AAAAAAAACAAAAAAA|819667|1461|31655|2452318|2452288|Dr.|Amy|Moses|Y|9|4|1966|TOGO||Amy.Moses@
  11. Ovk9KjHH.com|2452318|
  12. 3|AAAAAAAADAAAAAAA|1473522|6247|48572|2449130|2449100|Miss|Latisha|Hamilton|N|18|9|1979|NIUE||
  13. Latisha.Hamilton@V.com|2452313|
  14. 4|AAAAAAAAEAAAAAAA|1703214|3986|39558|2450030|2450000|Dr.|Michael|White|N|7|6|1983|MEXICO||Mic
  15. hael.White@i.org|2452361|
  16. 5|AAAAAAAAFAAAAAAA|953372|4470|36368|2449438|2449408|Sir|Robert|Moran|N|8|5|1956|FIJI||Robert.
  17. Moran@Hh.edu|2452469|
  18. ...

Here is a SQL script to set up Impala tables pointing to some of these data files in HDFS. (The script in the VM sets up tables like this through Hive; ignore those tables for purposes of this demonstration.) Save the following as customer_setup.sql:

  1. --
  2. -- store_sales fact table and surrounding dimension tables only
  3. --
  4. create database tpcds;
  5. use tpcds;
  6. drop table if exists customer;
  7. create external table customer
  8. (
  9. c_customer_sk int,
  10. c_customer_id string,
  11. c_current_cdemo_sk int,
  12. c_current_hdemo_sk int,
  13. c_current_addr_sk int,
  14. c_first_shipto_date_sk int,
  15. c_first_sales_date_sk int,
  16. c_salutation string,
  17. c_first_name string,
  18. c_last_name string,
  19. c_preferred_cust_flag string,
  20. c_birth_day int,
  21. c_birth_month int,
  22. c_birth_year int,
  23. c_birth_country string,
  24. c_login string,
  25. c_email_address string,
  26. c_last_review_date string
  27. )
  28. row format delimited fields terminated by '|'
  29. location '/user/hive/tpcds/customer';
  30. drop table if exists customer_address;
  31. create external table customer_address
  32. (
  33. ca_address_sk int,
  34. ca_address_id string,
  35. ca_street_number string,
  36. ca_street_name string,
  37. ca_street_type string,
  38. ca_suite_number string,
  39. ca_city string,
  40. ca_county string,
  41. ca_state string,
  42. ca_zip string,
  43. ca_country string,
  44. ca_gmt_offset float,
  45. ca_location_type string
  46. )
  47. row format delimited fields terminated by '|'
  48. location '/user/hive/tpcds/customer_address';

We would run this script with a command such as:

  1. impala-shell -i localhost -f customer_setup.sql

Describe the Impala Table

Now that you have updated the database metadata that Impala caches, you can confirm that the expected tables are accessible by Impala and examine the attributes of one of the tables. We created these tables in the database named default. If the tables were in a database other than the default, we would issue a command use db_name to switch to that database before examining or querying its tables. We could also qualify the name of a table by prepending the database name, for example default.customer and default.customer_name.

  1. [impala-host:21000] > show databases
  2. Query finished, fetching results ...
  3. default
  4. Returned 1 row(s) in 0.00s
  5. [impala-host:21000] > show tables
  6. Query finished, fetching results ...
  7. customer
  8. customer_address
  9. Returned 2 row(s) in 0.00s
  10. [impala-host:21000] > describe customer_address
  11. +------------------+--------+---------+
  12. | name | type | comment |
  13. +------------------+--------+---------+
  14. | ca_address_sk | int | |
  15. | ca_address_id | string | |
  16. | ca_street_number | string | |
  17. | ca_street_name | string | |
  18. | ca_street_type | string | |
  19. | ca_suite_number | string | |
  20. | ca_city | string | |
  21. | ca_county | string | |
  22. | ca_state | string | |
  23. | ca_zip | string | |
  24. | ca_country | string | |
  25. | ca_gmt_offset | float | |
  26. | ca_location_type | string | |
  27. +------------------+--------+---------+
  28. Returned 13 row(s) in 0.01

Query the Impala Table

You can query data contained in the tables. Impala coordinates the query execution across a single node or multiple nodes depending on your configuration, without the overhead of running MapReduce jobs to perform the intermediate processing.

There are a variety of ways to execute queries on Impala:

  • Using the impala-shell command in interactive mode:

    1. $ impala-shell -i impala-host
    2. Connected to localhost:21000
    3. [impala-host:21000] > select count(*) from customer_address;
    4. 50000
    5. Returned 1 row(s) in 0.37s
  • Passing a set of commands contained in a file:

    1. $ impala-shell -i impala-host -f myquery.sql
    2. Connected to localhost:21000
    3. 50000
    4. Returned 1 row(s) in 0.19s
  • Passing a single command to the impala-shell command. The query is executed, the results are returned, and the shell exits. Make sure to quote the command, preferably with single quotation marks to avoid shell expansion of characters such as *.

    1. $ impala-shell -i impala-host -q 'select count(*) from customer_address'
    2. Connected to localhost:21000
    3. 50000
    4. Returned 1 row(s) in 0.29s

Data Loading and Querying Examples

This section describes how to create some sample tables and load data into them. These tables can then be queried using the Impala shell.

Loading Data

Loading data involves:

  • Establishing a data set. The example below uses .csv files.
  • Creating tables to which to load data.
  • Loading the data into the tables you created.

Sample Queries

To run these sample queries, create a SQL query file query.sql, copy and paste each query into the query file, and then run the query file using the shell. For example, to run query.sql on impala-host, you might use the command:

  1. impala-shell.sh -i impala-host -f query.sql

The examples and results below assume you have loaded the sample data into the tables as described above.

Example: Examining Contents of Tables

Let’s start by verifying that the tables do contain the data we expect. Because Impala often deals with tables containing millions or billions of rows, when examining tables of unknown size, include the LIMIT clause to avoid huge amounts of unnecessary output, as in the final query. (If your interactive query starts displaying an unexpected volume of data, press Ctrl-C in impala-shell to cancel the query.)

  1. SELECT * FROM tab1;
  2. SELECT * FROM tab2;
  3. SELECT * FROM tab2 LIMIT 5;

Results:

  1. +----+-------+------------+-------------------------------+
  2. | id | col_1 | col_2 | col_3 |
  3. +----+-------+------------+-------------------------------+
  4. | 1 | true | 123.123 | 2012-10-24 08:55:00 |
  5. | 2 | false | 1243.5 | 2012-10-25 13:40:00 |
  6. | 3 | false | 24453.325 | 2008-08-22 09:33:21.123000000 |
  7. | 4 | false | 243423.325 | 2007-05-12 22:32:21.334540000 |
  8. | 5 | true | 243.325 | 1953-04-22 09:11:33 |
  9. +----+-------+------------+-------------------------------+
  10. +----+-------+---------------+
  11. | id | col_1 | col_2 |
  12. +----+-------+---------------+
  13. | 1 | true | 12789.123 |
  14. | 2 | false | 1243.5 |
  15. | 3 | false | 24453.325 |
  16. | 4 | false | 2423.3254 |
  17. | 5 | true | 243.325 |
  18. | 60 | false | 243565423.325 |
  19. | 70 | true | 243.325 |
  20. | 80 | false | 243423.325 |
  21. | 90 | true | 243.325 |
  22. +----+-------+---------------+
  23. +----+-------+-----------+
  24. | id | col_1 | col_2 |
  25. +----+-------+-----------+
  26. | 1 | true | 12789.123 |
  27. | 2 | false | 1243.5 |
  28. | 3 | false | 24453.325 |
  29. | 4 | false | 2423.3254 |
  30. | 5 | true | 243.325 |
  31. +----+-------+-----------+
Example: Aggregate and Join
  1. SELECT tab1.col_1, MAX(tab2.col_2), MIN(tab2.col_2)
  2. FROM tab2 JOIN tab1 USING (id)
  3. GROUP BY col_1 ORDER BY 1 LIMIT 5;

Results:

  1. +-------+-----------------+-----------------+
  2. | col_1 | max(tab2.col_2) | min(tab2.col_2) |
  3. +-------+-----------------+-----------------+
  4. | false | 24453.325 | 1243.5 |
  5. | true | 12789.123 | 243.325 |
  6. +-------+-----------------+-----------------+
Example: Subquery, Aggregate and Joins
  1. SELECT tab2.*
  2. FROM tab2,
  3. (SELECT tab1.col_1, MAX(tab2.col_2) AS max_col2
  4. FROM tab2, tab1
  5. WHERE tab1.id = tab2.id
  6. GROUP BY col_1) subquery1
  7. WHERE subquery1.max_col2 = tab2.col_2;

Results:

  1. +----+-------+-----------+
  2. | id | col_1 | col_2 |
  3. +----+-------+-----------+
  4. | 1 | true | 12789.123 |
  5. | 3 | false | 24453.325 |
  6. +----+-------+-----------+
Example: INSERT Query
  1. INSERT OVERWRITE TABLE tab3
  2. SELECT id, col_1, col_2, MONTH(col_3), DAYOFMONTH(col_3)
  3. FROM tab1 WHERE YEAR(col_3) = 2012;

Query TAB3 to check the result:

  1. SELECT * FROM tab3;

Results:

  1. +----+-------+---------+-------+-----+
  2. | id | col_1 | col_2 | month | day |
  3. +----+-------+---------+-------+-----+
  4. | 1 | true | 123.123 | 10 | 24 |
  5. | 2 | false | 1243.5 | 10 | 25 |
  6. +----+-------+---------+-------+-----+

Advanced Tutorials

These tutorials walk you through advanced scenarios or specialized features.

Attaching an External Partitioned Table to an HDFS Directory Structure

This tutorial shows how you might set up a directory tree in HDFS, put data files into the lowest-level subdirectories, and then use an Impala external table to query the data files from their original locations.

The tutorial uses a table with web log data, with separate subdirectories for the year, month, day, and host. For simplicity, we use a tiny amount of CSV data, loading the same data into each partition.

First, we make an Impala partitioned table for CSV data, and look at the underlying HDFS directory structure to understand the directory structure to re-create elsewhere in HDFS. The columns field1, field2, and field3 correspond to the contents of the CSV data files. The year, month, day, and host columns are all represented as subdirectories within the table structure, and are not part of the CSV files. We use STRING for each of these columns so that we can produce consistent subdirectory names, with leading zeros for a consistent length.

  1. create database external_partitions;
  2. use external_partitions;
  3. create table logs (field1 string, field2 string, field3 string)
  4. partitioned by (year string, month string , day string, host string)
  5. row format delimited fields terminated by ',';
  6. insert into logs partition (year="2013", month="07", day="28", host="host1") values ("foo","foo","foo");
  7. insert into logs partition (year="2013", month="07", day="28", host="host2") values ("foo","foo","foo");
  8. insert into logs partition (year="2013", month="07", day="29", host="host1") values ("foo","foo","foo");
  9. insert into logs partition (year="2013", month="07", day="29", host="host2") values ("foo","foo","foo");
  10. insert into logs partition (year="2013", month="08", day="01", host="host1") values ("foo","foo","foo");

Back in the Linux shell, we examine the HDFS directory structure. (Your Impala data directory might be in a different location; for historical reasons, it is sometimes under the HDFS path /user/hive/warehouse.) We use the hdfs dfs -ls command to examine the nested subdirectories corresponding to each partitioning column, with separate subdirectories at each level (with = in their names) representing the different values for each partitioning column. When we get to the lowest level of subdirectory, we use the hdfs dfs -cat command to examine the data file and see CSV-formatted data produced by the INSERT statement in Impala.

  1. $ hdfs dfs -ls /user/impala/warehouse/external_partitions.db
  2. Found 1 items
  3. drwxrwxrwt - impala hive 0 2013-08-07 12:24 /user/impala/warehouse/external_partitions.db/logs
  4. $ hdfs dfs -ls /user/impala/warehouse/external_partitions.db/logs
  5. Found 1 items
  6. drwxr-xr-x - impala hive 0 2013-08-07 12:24 /user/impala/warehouse/external_partitions.db/logs/year=2013
  7. $ hdfs dfs -ls /user/impala/warehouse/external_partitions.db/logs/year=2013
  8. Found 2 items
  9. drwxr-xr-x - impala hive 0 2013-08-07 12:23 /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07
  10. drwxr-xr-x - impala hive 0 2013-08-07 12:24 /user/impala/warehouse/external_partitions.db/logs/year=2013/month=08
  11. $ hdfs dfs -ls /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07
  12. Found 2 items
  13. drwxr-xr-x - impala hive 0 2013-08-07 12:22 /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07/day=28
  14. drwxr-xr-x - impala hive 0 2013-08-07 12:23 /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07/day=29
  15. $ hdfs dfs -ls /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07/day=28
  16. Found 2 items
  17. drwxr-xr-x - impala hive 0 2013-08-07 12:21 /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07/day=28/host=host1
  18. drwxr-xr-x - impala hive 0 2013-08-07 12:22 /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07/day=28/host=host2
  19. $ hdfs dfs -ls /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07/day=28/host=host1
  20. Found 1 items
  21. -rw-r--r-- 3 impala hive 12 2013-08-07 12:21 /user/impala/warehouse/external_partiti
  22. ons.db/logs/year=2013/month=07/day=28/host=host1/3981726974111751120--8907184999369517436_822630111_data.0
  23. $ hdfs dfs -cat /user/impala/warehouse/external_partitions.db/logs/year=2013/month=07/day=28/\
  24. host=host1/3981726974111751120--8 907184999369517436_822630111_data.0
  25. foo,foo,foo

Still in the Linux shell, we use hdfs dfs -mkdir to create several data directories outside the HDFS directory tree that Impala controls (/user/impala/warehouse in this example, maybe different in your case). Depending on your configuration, you might need to log in as a user with permission to write into this HDFS directory tree; for example, the commands shown here were run while logged in as the hdfs user.

  1. $ hdfs dfs -mkdir -p /user/impala/data/logs/year=2013/month=07/day=28/host=host1
  2. $ hdfs dfs -mkdir -p /user/impala/data/logs/year=2013/month=07/day=28/host=host2
  3. $ hdfs dfs -mkdir -p /user/impala/data/logs/year=2013/month=07/day=28/host=host1
  4. $ hdfs dfs -mkdir -p /user/impala/data/logs/year=2013/month=07/day=29/host=host1
  5. $ hdfs dfs -mkdir -p /user/impala/data/logs/year=2013/month=08/day=01/host=host1

We make a tiny CSV file, with values different than in the INSERT statements used earlier, and put a copy within each subdirectory that we will use as an Impala partition.

  1. $ cat >dummy_log_data
  2. bar,baz,bletch
  3. $ hdfs dfs -mkdir -p /user/impala/data/external_partitions/year=2013/month=08/day=01/host=host1
  4. $ hdfs dfs -mkdir -p /user/impala/data/external_partitions/year=2013/month=07/day=28/host=host1
  5. $ hdfs dfs -mkdir -p /user/impala/data/external_partitions/year=2013/month=07/day=28/host=host2
  6. $ hdfs dfs -mkdir -p /user/impala/data/external_partitions/year=2013/month=07/day=29/host=host1
  7. $ hdfs dfs -put dummy_log_data /user/impala/data/logs/year=2013/month=07/day=28/host=host1
  8. $ hdfs dfs -put dummy_log_data /user/impala/data/logs/year=2013/month=07/day=28/host=host2
  9. $ hdfs dfs -put dummy_log_data /user/impala/data/logs/year=2013/month=07/day=29/host=host1
  10. $ hdfs dfs -put dummy_log_data /user/impala/data/logs/year=2013/month=08/day=01/host=host1

Back in the impala-shell interpreter, we move the original Impala-managed table aside, and create a new external table with a LOCATION clause pointing to the directory under which we have set up all the partition subdirectories and data files.

  1. use external_partitions;
  2. alter table logs rename to logs_original;
  3. create external table logs (field1 string, field2 string, field3 string)
  4. partitioned by (year string, month string, day string, host string)
  5. row format delimited fields terminated by ','
  6. location '/user/impala/data/logs';

Because partition subdirectories and data files come and go during the data lifecycle, you must identify each of the partitions through an ALTER TABLE statement before Impala recognizes the data files they contain.

  1. alter table logs add partition (year="2013",month="07",day="28",host="host1")
  2. alter table log_type add partition (year="2013",month="07",day="28",host="host2");
  3. alter table log_type add partition (year="2013",month="07",day="29",host="host1");
  4. alter table log_type add partition (year="2013",month="08",day="01",host="host1");

We issue a REFRESH statement for the table, always a safe practice when data files have been manually added, removed, or changed. Then the data is ready to be queried. The SELECT * statement illustrates that the data from our trivial CSV file was recognized in each of the partitions where we copied it. Although in this case there are only a few rows, we include a LIMIT clause on this test query just in case there is more data than we expect.

  1. refresh log_type;
  2. select * from log_type limit 100;
  3. +--------+--------+--------+------+-------+-----+-------+
  4. | field1 | field2 | field3 | year | month | day | host |
  5. +--------+--------+--------+------+-------+-----+-------+
  6. | bar | baz | bletch | 2013 | 07 | 28 | host1 |
  7. | bar | baz | bletch | 2013 | 08 | 01 | host1 |
  8. | bar | baz | bletch | 2013 | 07 | 29 | host1 |
  9. | bar | baz | bletch | 2013 | 07 | 28 | host2 |
  10. +--------+--------+--------+------+-------+-----+-------+

Switching Back and Forth Between Impala and Hive

Sometimes, you might find it convenient to switch to the Hive shell to perform some data loading or transformation operation, particularly on file formats such as RCFile, SequenceFile, and Avro that Impala currently can query but not write to.

Whenever you create, drop, or alter a table or other kind of object through Hive, the next time you switch back to the impala-shell interpreter, issue a one-time INVALIDATE METADATA statement so that Impala recognizes the new or changed object.

Whenever you load, insert, or change data in an existing table through Hive (or even through manual HDFS operations such as the hdfs command), the next time you switch back to the impala-shell interpreter, issue a one-time REFRESH table_name statement so that Impala recognizes the new or changed data.

For examples showing how this process works for the REFRESH statement, look at the examples of creating RCFile and SequenceFile tables in Impala, loading data through Hive, and then querying the data through Impala. See Using the RCFile File Format with Impala Tables and Using the SequenceFile File Format with Impala Tables for those examples.

For examples showing how this process works for the INVALIDATE METADATA statement, look at the example of creating and loading an Avro table in Hive, and then querying the data through Impala. See Using the Avro File Format with Impala Tables for that example.

Note:

Originally, Impala did not support UDFs, but this feature is available in Impala starting in Impala 1.2. Some INSERT ... SELECT transformations that you originally did through Hive can now be done through Impala. See Impala User-Defined Functions (UDFs) for details.

Prior to Impala 1.2, the REFRESH and INVALIDATE METADATA statements needed to be issued on each Impala node to which you connected and issued queries. In Impala 1.2 and higher, when you issue either of those statements on any Impala node, the results are broadcast to all the Impala nodes in the cluster, making it truly a one-step operation after each round of DDL or ETL operations in Hive.

Cross Joins and Cartesian Products with the CROSS JOIN Operator

Originally, Impala restricted join queries so that they had to include at least one equality comparison between the columns of the tables on each side of the join operator. With the huge tables typically processed by Impala, any miscoded query that produced a full Cartesian product as a result set could consume a huge amount of cluster resources.

In Impala 1.2.2 and higher, this restriction is lifted when you use the CROSS JOIN operator in the query. You still cannot remove all WHERE clauses from a query like SELECT * FROM t1 JOIN t2 to produce all combinations of rows from both tables. But you can use the CROSS JOIN operator to explicitly request such a Cartesian product. Typically, this operation is applicable for smaller tables, where the result set still fits within the memory of a single Impala node.

The following example sets up data for use in a series of comic books where characters battle each other. At first, we use an equijoin query, which only allows characters from the same time period and the same planet to meet.

  1. [localhost:21000] > create table heroes (name string, era string, planet string);
  2. [localhost:21000] > create table villains (name string, era string, planet string);
  3. [localhost:21000] > insert into heroes values
  4. > ('Tesla','20th century','Earth'),
  5. > ('Pythagoras','Antiquity','Earth'),
  6. > ('Zopzar','Far Future','Mars');
  7. Inserted 3 rows in 2.28s
  8. [localhost:21000] > insert into villains values
  9. > ('Caligula','Antiquity','Earth'),
  10. > ('John Dillinger','20th century','Earth'),
  11. > ('Xibulor','Far Future','Venus');
  12. Inserted 3 rows in 1.93s
  13. [localhost:21000] > select concat(heroes.name,' vs. ',villains.name) as battle
  14. > from heroes join villains
  15. > where heroes.era = villains.era and heroes.planet = villains.planet;
  16. +--------------------------+
  17. | battle |
  18. +--------------------------+
  19. | Tesla vs. John Dillinger |
  20. | Pythagoras vs. Caligula |
  21. +--------------------------+
  22. Returned 2 row(s) in 0.47s

Readers demanded more action, so we added elements of time travel and space travel so that any hero could face any villain. Prior to Impala 1.2.2, this type of query was impossible because all joins had to reference matching values between the two tables:

  1. [localhost:21000] > -- Cartesian product not possible in Impala 1.1.
  2. > select concat(heroes.name,' vs. ',villains.name) as battle from heroes join villains;
  3. ERROR: NotImplementedException: Join between 'heroes' and 'villains' requires at least one conjunctive equality predicate between the two tables

With Impala 1.2.2, we rewrite the query slightly to use CROSS JOIN rather than JOIN, and now the result set includes all combinations:

  1. [localhost:21000] > -- Cartesian product available in Impala 1.2.2 with the CROSS JOIN syntax.
  2. > select concat(heroes.name,' vs. ',villains.name) as battle from heroes cross join villains;
  3. +-------------------------------+
  4. | battle |
  5. +-------------------------------+
  6. | Tesla vs. Caligula |
  7. | Tesla vs. John Dillinger |
  8. | Tesla vs. Xibulor |
  9. | Pythagoras vs. Caligula |
  10. | Pythagoras vs. John Dillinger |
  11. | Pythagoras vs. Xibulor |
  12. | Zopzar vs. Caligula |
  13. | Zopzar vs. John Dillinger |
  14. | Zopzar vs. Xibulor |
  15. +-------------------------------+
  16. Returned 9 row(s) in 0.33s

The full combination of rows from both tables is known as the Cartesian product. This type of result set is often used for creating grid data structures. You can also filter the result set by including WHERE clauses that do not explicitly compare columns between the two tables. The following example shows how you might produce a list of combinations of year and quarter for use in a chart, and then a shorter list with only selected quarters.

  1. [localhost:21000] > create table x_axis (x int);
  2. [localhost:21000] > create table y_axis (y int);
  3. [localhost:21000] > insert into x_axis values (1),(2),(3),(4);
  4. Inserted 4 rows in 2.14s
  5. [localhost:21000] > insert into y_axis values (2010),(2011),(2012),(2013),(2014);
  6. Inserted 5 rows in 1.32s
  7. [localhost:21000] > select y as year, x as quarter from x_axis cross join y_axis;
  8. +------+---------+
  9. | year | quarter |
  10. +------+---------+
  11. | 2010 | 1 |
  12. | 2011 | 1 |
  13. | 2012 | 1 |
  14. | 2013 | 1 |
  15. | 2014 | 1 |
  16. | 2010 | 2 |
  17. | 2011 | 2 |
  18. | 2012 | 2 |
  19. | 2013 | 2 |
  20. | 2014 | 2 |
  21. | 2010 | 3 |
  22. | 2011 | 3 |
  23. | 2012 | 3 |
  24. | 2013 | 3 |
  25. | 2014 | 3 |
  26. | 2010 | 4 |
  27. | 2011 | 4 |
  28. | 2012 | 4 |
  29. | 2013 | 4 |
  30. | 2014 | 4 |
  31. +------+---------+
  32. Returned 20 row(s) in 0.38s
  33. [localhost:21000] > select y as year, x as quarter from x_axis cross join y_axis where x in (1,3);
  34. +------+---------+
  35. | year | quarter |
  36. +------+---------+
  37. | 2010 | 1 |
  38. | 2011 | 1 |
  39. | 2012 | 1 |
  40. | 2013 | 1 |
  41. | 2014 | 1 |
  42. | 2010 | 3 |
  43. | 2011 | 3 |
  44. | 2012 | 3 |
  45. | 2013 | 3 |
  46. | 2014 | 3 |
  47. +------+---------+
  48. Returned 10 row(s) in 0.39s

Dealing with Parquet Files with Unknown Schema

As data pipelines start to include more aspects such as NoSQL or loosely specified schemas, you might encounter situations where you have data files (particularly in Parquet format) where you do not know the precise table definition. This tutorial shows how you can build an Impala table around data that comes from non-Impala or even non-SQL sources, where you do not have control of the table layout and might not be familiar with the characteristics of the data.

The data used in this tutorial represents airline on-time arrival statistics, from October 1987 through April 2008. See the details on the 2009 ASA Data Expo web site. You can also see the explanations of the columns; for purposes of this exercise, wait until after following the tutorial before examining the schema, to better simulate a real-life situation where you cannot rely on assumptions and assertions about the ranges and representations of data values.

We will download Parquet files containing this data from the Ibis blog. First, we download and unpack the data files. There are 8 files totalling 1.4 GB. Each file is less than 256 MB.

  1. $ wget -O airlines_parquet.tar.gz https://www.dropbox.com/s/ol9x51tqp6cv4yc/airlines_parquet.tar.gz?dl=0
  2. ...
  3. Length: 1245204740 (1.2G) [application/octet-stream]
  4. Saving to: airlines_parquet.tar.gz
  5. 2015-08-12 17:14:24 (23.6 MB/s) - airlines_parquet.tar.gz saved [1245204740/1245204740]
  6. $ tar xvzf airlines_parquet.tar.gz
  7. airlines_parquet/
  8. airlines_parquet/93459d994898a9ba-77674173b331fa9a_2073981944_data.0.parq
  9. airlines_parquet/93459d994898a9ba-77674173b331fa99_1555718317_data.1.parq
  10. airlines_parquet/93459d994898a9ba-77674173b331fa99_1555718317_data.0.parq
  11. airlines_parquet/93459d994898a9ba-77674173b331fa96_2118228804_data.0.parq
  12. airlines_parquet/93459d994898a9ba-77674173b331fa97_574780876_data.0.parq
  13. airlines_parquet/93459d994898a9ba-77674173b331fa96_2118228804_data.1.parq
  14. airlines_parquet/93459d994898a9ba-77674173b331fa98_1194408366_data.0.parq
  15. airlines_parquet/93459d994898a9ba-77674173b331fa9b_1413430552_data.0.parq
  16. $ cd airlines_parquet/
  17. $ du -kch *.parq
  18. 253M 93459d994898a9ba-77674173b331fa96_2118228804_data.0.parq
  19. 65M 93459d994898a9ba-77674173b331fa96_2118228804_data.1.parq
  20. 156M 93459d994898a9ba-77674173b331fa97_574780876_data.0.parq
  21. 240M 93459d994898a9ba-77674173b331fa98_1194408366_data.0.parq
  22. 253M 93459d994898a9ba-77674173b331fa99_1555718317_data.0.parq
  23. 16M 93459d994898a9ba-77674173b331fa99_1555718317_data.1.parq
  24. 177M 93459d994898a9ba-77674173b331fa9a_2073981944_data.0.parq
  25. 213M 93459d994898a9ba-77674173b331fa9b_1413430552_data.0.parq
  26. 1.4G total

Next, we put the Parquet data files in HDFS, all together in a single directory, with permissions on the directory and the files so that the impala user will be able to read them.

Note: After unpacking, we saw the largest Parquet file was 253 MB. When copying Parquet files into HDFS for Impala to use, for maximum query performance, make sure that each file resides in a single HDFS data block. Therefore, we pick a size larger than any single file and specify that as the block size, using the argument -Ddfs.block.size=256m on the hdfs dfs -put command.

  1. $ hdfs dfs -mkdir -p hdfs://demo_host.example.com:8020/user/impala/staging/airlines
  2. $ hdfs dfs -Ddfs.block.size=256m -put *.parq /user/impala/staging/airlines
  3. $ hdfs dfs -ls /user/impala/staging
  4. Found 1 items
  5. drwxrwxrwx - hdfs supergroup 0 2015-08-12 13:52 /user/impala/staging/airlines
  6. $ hdfs dfs -ls hdfs://demo_host.example.com:8020/user/impala/staging/airlines
  7. Found 8 items
  8. -rw-r--r-- 3 jrussell supergroup 265107489 2015-08-12 17:18 /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa96_2118228804_data.0.parq
  9. -rw-r--r-- 3 jrussell supergroup 67544715 2015-08-12 17:18 /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa96_2118228804_data.1.parq
  10. -rw-r--r-- 3 jrussell supergroup 162556490 2015-08-12 17:18 /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa97_574780876_data.0.parq
  11. -rw-r--r-- 3 jrussell supergroup 251603518 2015-08-12 17:18 /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa98_1194408366_data.0.parq
  12. -rw-r--r-- 3 jrussell supergroup 265186603 2015-08-12 17:18 /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa99_1555718317_data.0.parq
  13. -rw-r--r-- 3 jrussell supergroup 16663754 2015-08-12 17:18 /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa99_1555718317_data.1.parq
  14. -rw-r--r-- 3 jrussell supergroup 185511677 2015-08-12 17:18 /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa9a_2073981944_data.0.parq
  15. -rw-r--r-- 3 jrussell supergroup 222794621 2015-08-12 17:18 /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa9b_1413430552_data.0.parq

With the files in an accessible location in HDFS, we create a database table that uses the data in those files. The CREATE EXTERNAL syntax and the LOCATION attribute point Impala at the appropriate HDFS directory. The LIKE PARQUET 'path_to_any_parquet_file' clause means we skip the list of column names and types; Impala automatically gets the column names and data types straight from the data files. (Currently, this technique only works for Parquet files.) We ignore the warning about lack of READ_WRITE access to the files in HDFS; the impala user can read the files, which will be sufficient for us to experiment with queries and perform some copy and transform operations into other tables.

  1. $ impala-shell -i localhost
  2. Starting Impala Shell without Kerberos authentication
  3. Connected to localhost:21000
  4. Server version: impalad version 2.8.x (build
  5. x.y.z)
  6. Welcome to the Impala shell. Press TAB twice to see a list of available commands.
  7. ...
  8. (Shell
  9. build version: Impala Shell v3.0.x (hash) built on
  10. date)
  11. [localhost:21000] > create database airline_data;
  12. [localhost:21000] > use airline_data;
  13. [localhost:21000] > create external table airlines_external
  14. > like parquet 'hdfs://demo_host.example.com:8020/user/impala/staging/airlines/93459d994898a9ba-77674173b331fa96_2118228804_data.0.parq'
  15. > stored as parquet location 'hdfs://demo_host.example.com:8020/user/impala/staging/airlines';
  16. WARNINGS: Impala does not have READ_WRITE access to path 'hdfs://demo_host.example.com:8020/user/impala/staging'

With the table created, we examine its physical and logical characteristics to confirm that the data is really there and in a format and shape that we can work with. The SHOW TABLE STATS statement gives a very high-level summary of the table, showing how many files and how much total data it contains. Also, it confirms that the table is expecting all the associated data files to be in Parquet format. (The ability to work with all kinds of HDFS data files in different formats means that it is possible to have a mismatch between the format of the data files, and the format that the table expects the data files to be in.) The SHOW FILES statement confirms that the data in the table has the expected number, names, and sizes of the original Parquet files. The DESCRIBE statement (or its abbreviation DESC) confirms the names and types of the columns that Impala automatically created after reading that metadata from the Parquet file. The DESCRIBE FORMATTED statement prints out some extra detail along with the column definitions; the pieces we care about for this exercise are the containing database for the table, the location of the associated data files in HDFS, the fact that it’s an external table so Impala will not delete the HDFS files when we finish the experiments and drop the table, and the fact that the table is set up to work exclusively with files in the Parquet format.

  1. [localhost:21000] > show table stats airlines_external;
  2. +-------+--------+--------+--------------+-------------------+---------+-------------------+
  3. | #Rows | #Files | Size | Bytes Cached | Cache Replication | Format | Incremental stats |
  4. +-------+--------+--------+--------------+-------------------+---------+-------------------+
  5. | -1 | 8 | 1.34GB | NOT CACHED | NOT CACHED | PARQUET | false |
  6. +-------+--------+--------+--------------+-------------------+---------+-------------------+
  7. [localhost:21000] > show files in airlines_external;
  8. +----------------------------------------------------------------------------------------+----------+-----------+
  9. | path | size | partition |
  10. +----------------------------------------------------------------------------------------+----------+-----------+
  11. | /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa96_2118228804_data.0.parq | 252.83MB | |
  12. | /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa96_2118228804_data.1.parq | 64.42MB | |
  13. | /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa97_574780876_data.0.parq | 155.03MB | |
  14. | /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa98_1194408366_data.0.parq | 239.95MB | |
  15. | /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa99_1555718317_data.0.parq | 252.90MB | |
  16. | /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa99_1555718317_data.1.parq | 15.89MB | |
  17. | /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa9a_2073981944_data.0.parq | 176.92MB | |
  18. | /user/impala/staging/airlines/93459d994898a9ba-77674173b331fa9b_1413430552_data.0.parq | 212.47MB | |
  19. +----------------------------------------------------------------------------------------+----------+-----------+
  20. [localhost:21000] > describe airlines_external;
  21. +---------------------+--------+---------------------------------------------------+
  22. | name | type | comment |
  23. +---------------------+--------+---------------------------------------------------+
  24. | year | int | inferred from: optional int32 year |
  25. | month | int | inferred from: optional int32 month |
  26. | day | int | inferred from: optional int32 day |
  27. | dayofweek | int | inferred from: optional int32 dayofweek |
  28. | dep_time | int | inferred from: optional int32 dep_time |
  29. | crs_dep_time | int | inferred from: optional int32 crs_dep_time |
  30. | arr_time | int | inferred from: optional int32 arr_time |
  31. | crs_arr_time | int | inferred from: optional int32 crs_arr_time |
  32. | carrier | string | inferred from: optional binary carrier |
  33. | flight_num | int | inferred from: optional int32 flight_num |
  34. | tail_num | int | inferred from: optional int32 tail_num |
  35. | actual_elapsed_time | int | inferred from: optional int32 actual_elapsed_time |
  36. | crs_elapsed_time | int | inferred from: optional int32 crs_elapsed_time |
  37. | airtime | int | inferred from: optional int32 airtime |
  38. | arrdelay | int | inferred from: optional int32 arrdelay |
  39. | depdelay | int | inferred from: optional int32 depdelay |
  40. | origin | string | inferred from: optional binary origin |
  41. | dest | string | inferred from: optional binary dest |
  42. | distance | int | inferred from: optional int32 distance |
  43. | taxi_in | int | inferred from: optional int32 taxi_in |
  44. | taxi_out | int | inferred from: optional int32 taxi_out |
  45. | cancelled | int | inferred from: optional int32 cancelled |
  46. | cancellation_code | string | inferred from: optional binary cancellation_code |
  47. | diverted | int | inferred from: optional int32 diverted |
  48. | carrier_delay | int | inferred from: optional int32 carrier_delay |
  49. | weather_delay | int | inferred from: optional int32 weather_delay |
  50. | nas_delay | int | inferred from: optional int32 nas_delay |
  51. | security_delay | int | inferred from: optional int32 security_delay |
  52. | late_aircraft_delay | int | inferred from: optional int32 late_aircraft_delay |
  53. +---------------------+--------+---------------------------------------------------+
  54. [localhost:21000] > desc formatted airlines_external;
  55. +------------------------------+-------------------------------
  56. | name | type
  57. +------------------------------+-------------------------------
  58. ...
  59. | # Detailed Table Information | NULL
  60. | Database: | airline_data
  61. | Owner: | jrussell
  62. ...
  63. | Location: | /user/impala/staging/airlines
  64. | Table Type: | EXTERNAL_TABLE
  65. ...
  66. | # Storage Information | NULL
  67. | SerDe Library: | parquet.hive.serde.ParquetHiveSerDe
  68. | InputFormat: | parquet.hive.DeprecatedParquetInputFormat
  69. | OutputFormat: | parquet.hive.DeprecatedParquetOutputFormat
  70. ...

Now that we are confident that the connections are solid between the Impala table and the underlying Parquet files, we run some initial queries to understand the characteristics of the data: the overall number of rows, and the ranges and how many different values are in certain columns. For convenience in understanding the magnitude of the COUNT(*) result, we run another query dividing the number of rows by 1 million, demonstrating that there are 123 million rows in the table.

  1. [localhost:21000] > select count(*) from airlines_external;
  2. +-----------+
  3. | count(*) |
  4. +-----------+
  5. | 123534969 |
  6. +-----------+
  7. Fetched 1 row(s) in 1.32s
  8. [localhost:21000] > select count(*) / 1e6 as 'millions of rows' from airlines_external;
  9. +------------------+
  10. | millions of rows |
  11. +------------------+
  12. | 123.534969 |
  13. +------------------+
  14. Fetched 1 row(s) in 1.24s

The NDV() function stands for “number of distinct values”, which for performance reasons is an estimate when there are lots of different values in the column, but is precise when the cardinality is less than 16 K. Use NDV() calls for this kind of exploration rather than COUNT(DISTINCT colname), because Impala can evaluate multiple NDV() functions in a single query, but only a single instance of COUNT DISTINCT. Here we see that there are modest numbers of different airlines, flight numbers, and origin and destination airports. Two things jump out from this query: the number of tail_num values is much smaller than we might have expected, and there are more destination airports than origin airports. Let’s dig further. What we find is that most tail_num values are NULL. It looks like this was an experimental column that wasn’t filled in accurately. We make a mental note that if we use this data as a starting point, we’ll ignore this column. We also find that certain airports are represented in the ORIGIN column but not the DEST column; now we know that we cannot rely on the assumption that those sets of airport codes are identical.

Note: A slight digression for some performance tuning. Notice how the first SELECT DISTINCT DEST query takes almost 40 seconds. We expect all queries on such a small data set, less than 2 GB, to take a few seconds at most. The reason is because the expression NOT IN (SELECT origin FROM airlines_external) produces an intermediate result set of 123 million rows, then runs 123 million comparisons on each data node against the tiny set of destination airports. The way the NOT IN operator works internally means that this intermediate result set with 123 million rows might be transmitted across the network to each data node in the cluster. Applying another DISTINCT inside the NOT IN subquery means that the intermediate result set is only 340 items, resulting in much less network traffic and fewer comparison operations. The more efficient query with the added DISTINCT is approximately 7 times as fast.

  1. [localhost:21000] > select ndv(carrier), ndv(flight_num), ndv(tail_num),
  2. > ndv(origin), ndv(dest) from airlines_external;
  3. +--------------+-----------------+---------------+-------------+-----------+
  4. | ndv(carrier) | ndv(flight_num) | ndv(tail_num) | ndv(origin) | ndv(dest) |
  5. +--------------+-----------------+---------------+-------------+-----------+
  6. | 29 | 9086 | 3 | 340 | 347 |
  7. +--------------+-----------------+---------------+-------------+-----------+
  8. [localhost:21000] > select tail_num, count(*) as howmany from airlines_external
  9. > group by tail_num;
  10. +----------+-----------+
  11. | tail_num | howmany |
  12. +----------+-----------+
  13. | 715 | 1 |
  14. | 0 | 406405 |
  15. | 112 | 6562 |
  16. | NULL | 123122001 |
  17. +----------+-----------+
  18. Fetched 1 row(s) in 5.18s
  19. [localhost:21000] > select distinct dest from airlines_external
  20. > where dest not in (select origin from airlines_external);
  21. +------+
  22. | dest |
  23. +------+
  24. | LBF |
  25. | CBM |
  26. | RCA |
  27. | SKA |
  28. | LAR |
  29. +------+
  30. Fetched 5 row(s) in 39.64s
  31. [localhost:21000] > select distinct dest from airlines_external
  32. > where dest not in (select distinct origin from airlines_external);
  33. +------+
  34. | dest |
  35. +------+
  36. | LBF |
  37. | RCA |
  38. | CBM |
  39. | SKA |
  40. | LAR |
  41. +------+
  42. Fetched 5 row(s) in 5.59s
  43. [localhost:21000] > select distinct origin from airlines_external
  44. > where origin not in (select distinct dest from airlines_external);
  45. Fetched 0 row(s) in 5.37s

Next, we try doing a simple calculation, with results broken down by year. This reveals that some years have no data in the AIRTIME column. That means we might be able to use that column in queries involving certain date ranges, but we cannot count on it to always be reliable. The question of whether a column contains any NULL values, and if so what is their number, proportion, and distribution, comes up again and again when doing initial exploration of a data set.

  1. [localhost:21000] > select year, sum(airtime) from airlines_external
  2. > group by year order by year desc;
  3. +------+--------------+
  4. | year | sum(airtime) |
  5. +------+--------------+
  6. | 2008 | 713050445 |
  7. | 2007 | 748015545 |
  8. | 2006 | 720372850 |
  9. | 2005 | 708204026 |
  10. | 2004 | 714276973 |
  11. | 2003 | 665706940 |
  12. | 2002 | 549761849 |
  13. | 2001 | 590867745 |
  14. | 2000 | 583537683 |
  15. | 1999 | 561219227 |
  16. | 1998 | 538050663 |
  17. | 1997 | 536991229 |
  18. | 1996 | 519440044 |
  19. | 1995 | 513364265 |
  20. | 1994 | NULL |
  21. | 1993 | NULL |
  22. | 1992 | NULL |
  23. | 1991 | NULL |
  24. | 1990 | NULL |
  25. | 1989 | NULL |
  26. | 1988 | NULL |
  27. | 1987 | NULL |
  28. +------+--------------+

With the notion of NULL values in mind, let’s come back to the TAILNUM column that we discovered had a lot of NULLs. Let’s quantify the NULL and non-NULL values in that column for better understanding. First, we just count the overall number of rows versus the non-NULL values in that column. That initial result gives the appearance of relatively few non-NULL values, but we can break it down more clearly in a single query. Once we have the COUNT(*) and the COUNT(colname) numbers, we can encode that initial query in a WITH clause, then run a followon query that performs multiple arithmetic operations on those values. Seeing that only one-third of one percent of all rows have non-NULL values for the TAILNUM column clearly illustrates that that column is not of much use.

  1. [localhost:21000] > select count(*) as 'rows', count(tail_num) as 'non-null tail numbers'
  2. > from airlines_external;
  3. +-----------+-----------------------+
  4. | rows | non-null tail numbers |
  5. +-----------+-----------------------+
  6. | 123534969 | 412968 |
  7. +-----------+-----------------------+
  8. Fetched 1 row(s) in 1.51s
  9. [localhost:21000] > with t1 as
  10. > (select count(*) as 'rows', count(tail_num) as 'nonnull'
  11. > from airlines_external)
  12. > select `rows`, `nonnull`, `rows` - `nonnull` as 'nulls',
  13. > (`nonnull` / `rows`) * 100 as 'percentage non-null'
  14. > from t1;
  15. +-----------+---------+-----------+---------------------+
  16. | rows | nonnull | nulls | percentage non-null |
  17. +-----------+---------+-----------+---------------------+
  18. | 123534969 | 412968 | 123122001 | 0.3342923897119365 |
  19. +-----------+---------+-----------+---------------------+

By examining other columns using these techniques, we can form a mental picture of the way data is distributed throughout the table, and which columns are most significant for query purposes. For this tutorial, we focus mostly on the fields likely to hold discrete values, rather than columns such as ACTUAL_ELAPSED_TIME whose names suggest they hold measurements. We would dig deeper into those columns once we had a clear picture of which questions were worthwhile to ask, and what kinds of trends we might look for. For the final piece of initial exploration, let’s look at the YEAR column. A simple GROUP BY query shows that it has a well-defined range, a manageable number of distinct values, and relatively even distribution of rows across the different years.

  1. [localhost:21000] > select min(year), max(year), ndv(year) from airlines_external;
  2. +-----------+-----------+-----------+
  3. | min(year) | max(year) | ndv(year) |
  4. +-----------+-----------+-----------+
  5. | 1987 | 2008 | 22 |
  6. +-----------+-----------+-----------+
  7. Fetched 1 row(s) in 2.03s
  8. [localhost:21000] > select year, count(*) howmany from airlines_external
  9. > group by year order by year desc;
  10. +------+---------+
  11. | year | howmany |
  12. +------+---------+
  13. | 2008 | 7009728 |
  14. | 2007 | 7453215 |
  15. | 2006 | 7141922 |
  16. | 2005 | 7140596 |
  17. | 2004 | 7129270 |
  18. | 2003 | 6488540 |
  19. | 2002 | 5271359 |
  20. | 2001 | 5967780 |
  21. | 2000 | 5683047 |
  22. | 1999 | 5527884 |
  23. | 1998 | 5384721 |
  24. | 1997 | 5411843 |
  25. | 1996 | 5351983 |
  26. | 1995 | 5327435 |
  27. | 1994 | 5180048 |
  28. | 1993 | 5070501 |
  29. | 1992 | 5092157 |
  30. | 1991 | 5076925 |
  31. | 1990 | 5270893 |
  32. | 1989 | 5041200 |
  33. | 1988 | 5202096 |
  34. | 1987 | 1311826 |
  35. +------+---------+
  36. Fetched 22 row(s) in 2.13s

We could go quite far with the data in this initial raw format, just as we downloaded it from the web. If the data set proved to be useful and worth persisting in Impala for extensive queries, we might want to copy it to an internal table, letting Impala manage the data files and perhaps reorganizing a little for higher efficiency. In this next stage of the tutorial, we copy the original data into a partitioned table, still in Parquet format. Partitioning based on the YEAR column lets us run queries with clauses such as WHERE year = 2001 or WHERE year BETWEEN 1989 AND 1999, which can dramatically cut down on I/O by ignoring all the data from years outside the desired range. Rather than reading all the data and then deciding which rows are in the matching years, Impala can zero in on only the data files from specific YEAR partitions. To do this, Impala physically reorganizes the data files, putting the rows from each year into data files in a separate HDFS directory for each YEAR value. Along the way, we’ll also get rid of the TAIL_NUM column that proved to be almost entirely NULL.

The first step is to create a new table with a layout very similar to the original AIRLINES_EXTERNAL table. We’ll do that by reverse-engineering a CREATE TABLE statement for the first table, then tweaking it slightly to include a PARTITION BY clause for YEAR, and excluding the TAIL_NUM column. The SHOW CREATE TABLE statement gives us the starting point.

  1. [localhost:21000] > show create table airlines_external;
  2. +-------------------------------------------------------------------------------------
  3. | result
  4. +-------------------------------------------------------------------------------------
  5. | CREATE EXTERNAL TABLE airline_data.airlines_external (
  6. | year INT COMMENT 'inferred from: optional int32 year',
  7. | month INT COMMENT 'inferred from: optional int32 month',
  8. | day INT COMMENT 'inferred from: optional int32 day',
  9. | dayofweek INT COMMENT 'inferred from: optional int32 dayofweek',
  10. | dep_time INT COMMENT 'inferred from: optional int32 dep_time',
  11. | crs_dep_time INT COMMENT 'inferred from: optional int32 crs_dep_time',
  12. | arr_time INT COMMENT 'inferred from: optional int32 arr_time',
  13. | crs_arr_time INT COMMENT 'inferred from: optional int32 crs_arr_time',
  14. | carrier STRING COMMENT 'inferred from: optional binary carrier',
  15. | flight_num INT COMMENT 'inferred from: optional int32 flight_num',
  16. | tail_num INT COMMENT 'inferred from: optional int32 tail_num',
  17. | actual_elapsed_time INT COMMENT 'inferred from: optional int32 actual_elapsed_time',
  18. | crs_elapsed_time INT COMMENT 'inferred from: optional int32 crs_elapsed_time',
  19. | airtime INT COMMENT 'inferred from: optional int32 airtime',
  20. | arrdelay INT COMMENT 'inferred from: optional int32 arrdelay',
  21. | depdelay INT COMMENT 'inferred from: optional int32 depdelay',
  22. | origin STRING COMMENT 'inferred from: optional binary origin',
  23. | dest STRING COMMENT 'inferred from: optional binary dest',
  24. | distance INT COMMENT 'inferred from: optional int32 distance',
  25. | taxi_in INT COMMENT 'inferred from: optional int32 taxi_in',
  26. | taxi_out INT COMMENT 'inferred from: optional int32 taxi_out',
  27. | cancelled INT COMMENT 'inferred from: optional int32 cancelled',
  28. | cancellation_code STRING COMMENT 'inferred from: optional binary cancellation_code',
  29. | diverted INT COMMENT 'inferred from: optional int32 diverted',
  30. | carrier_delay INT COMMENT 'inferred from: optional int32 carrier_delay',
  31. | weather_delay INT COMMENT 'inferred from: optional int32 weather_delay',
  32. | nas_delay INT COMMENT 'inferred from: optional int32 nas_delay',
  33. | security_delay INT COMMENT 'inferred from: optional int32 security_delay',
  34. | late_aircraft_delay INT COMMENT 'inferred from: optional int32 late_aircraft_delay'
  35. | )
  36. | STORED AS PARQUET
  37. | LOCATION 'hdfs://a1730.example.com:8020/user/impala/staging/airlines'
  38. | TBLPROPERTIES ('numFiles'='0', 'COLUMN_STATS_ACCURATE'='false',
  39. | 'transient_lastDdlTime'='1439425228', 'numRows'='-1', 'totalSize'='0',
  40. | 'rawDataSize'='-1')
  41. +-------------------------------------------------------------------------------------
  42. Fetched 1 row(s) in 0.03s
  43. [localhost:21000] > quit;

Although we could edit that output into a new SQL statement, all the ASCII box characters make such editing inconvenient. To get a more stripped-down CREATE TABLE to start with, we restart the impala-shell command with the -B option, which turns off the box-drawing behavior.

  1. [localhost:21000] > quit;
  2. Goodbye jrussell
  3. $ impala-shell -i localhost -B -d airline_data;
  4. Starting Impala Shell without Kerberos authentication
  5. Connected to localhost:21000
  6. Server version: impalad version 2.8.x (build
  7. x.y.z)
  8. Welcome to the Impala shell. Press TAB twice to see a list of available commands.
  9. ...
  10. (Shell
  11. build version: Impala Shell v3.0.x (hash) built on
  12. date)
  13. [localhost:21000] > show create table airlines_external;
  14. "CREATE EXTERNAL TABLE airline_data.airlines_external (
  15. year INT COMMENT 'inferred from: optional int32 year',
  16. month INT COMMENT 'inferred from: optional int32 month',
  17. day INT COMMENT 'inferred from: optional int32 day',
  18. dayofweek INT COMMENT 'inferred from: optional int32 dayofweek',
  19. dep_time INT COMMENT 'inferred from: optional int32 dep_time',
  20. crs_dep_time INT COMMENT 'inferred from: optional int32 crs_dep_time',
  21. arr_time INT COMMENT 'inferred from: optional int32 arr_time',
  22. crs_arr_time INT COMMENT 'inferred from: optional int32 crs_arr_time',
  23. carrier STRING COMMENT 'inferred from: optional binary carrier',
  24. flight_num INT COMMENT 'inferred from: optional int32 flight_num',
  25. tail_num INT COMMENT 'inferred from: optional int32 tail_num',
  26. actual_elapsed_time INT COMMENT 'inferred from: optional int32 actual_elapsed_time',
  27. crs_elapsed_time INT COMMENT 'inferred from: optional int32 crs_elapsed_time',
  28. airtime INT COMMENT 'inferred from: optional int32 airtime',
  29. arrdelay INT COMMENT 'inferred from: optional int32 arrdelay',
  30. depdelay INT COMMENT 'inferred from: optional int32 depdelay',
  31. origin STRING COMMENT 'inferred from: optional binary origin',
  32. dest STRING COMMENT 'inferred from: optional binary dest',
  33. distance INT COMMENT 'inferred from: optional int32 distance',
  34. taxi_in INT COMMENT 'inferred from: optional int32 taxi_in',
  35. taxi_out INT COMMENT 'inferred from: optional int32 taxi_out',
  36. cancelled INT COMMENT 'inferred from: optional int32 cancelled',
  37. cancellation_code STRING COMMENT 'inferred from: optional binary cancellation_code',
  38. diverted INT COMMENT 'inferred from: optional int32 diverted',
  39. carrier_delay INT COMMENT 'inferred from: optional int32 carrier_delay',
  40. weather_delay INT COMMENT 'inferred from: optional int32 weather_delay',
  41. nas_delay INT COMMENT 'inferred from: optional int32 nas_delay',
  42. security_delay INT COMMENT 'inferred from: optional int32 security_delay',
  43. late_aircraft_delay INT COMMENT 'inferred from: optional int32 late_aircraft_delay'
  44. )
  45. STORED AS PARQUET
  46. LOCATION 'hdfs://a1730.example.com:8020/user/impala/staging/airlines'
  47. TBLPROPERTIES ('numFiles'='0', 'COLUMN_STATS_ACCURATE'='false',
  48. 'transient_lastDdlTime'='1439425228', 'numRows'='-1', 'totalSize'='0',
  49. 'rawDataSize'='-1')"
  50. Fetched 1 row(s) in 0.01s

After copying and pasting the CREATE TABLE statement into a text editor for fine-tuning, we quit and restart impala-shell without the -B option, to switch back to regular output.

Next we run the CREATE TABLE statement that we adapted from the SHOW CREATE TABLE output. We kept the STORED AS PARQUET clause because we want to rearrange the data somewhat but still keep it in the high-performance Parquet format. The LOCATION and TBLPROPERTIES clauses are not relevant for this new table, so we edit those out. Because we are going to partition the new table based on the YEAR column, we move that column name (and its type) into a new PARTITIONED BY clause.

  1. [localhost:21000] > CREATE TABLE airline_data.airlines
  2. > (
  3. > month INT,
  4. > day INT,
  5. > dayofweek INT,
  6. > dep_time INT,
  7. > crs_dep_time INT,
  8. > arr_time INT,
  9. > crs_arr_time INT,
  10. > carrier STRING,
  11. > flight_num INT,
  12. > actual_elapsed_time INT,
  13. > crs_elapsed_time INT,
  14. > airtime INT,
  15. > arrdelay INT,
  16. > depdelay INT,
  17. > origin STRING,
  18. > dest STRING,
  19. > distance INT,
  20. > taxi_in INT,
  21. > taxi_out INT,
  22. > cancelled INT,
  23. > cancellation_code STRING,
  24. > diverted INT,
  25. > carrier_delay INT,
  26. > weather_delay INT,
  27. > nas_delay INT,
  28. > security_delay INT,
  29. > late_aircraft_delay INT
  30. > )
  31. > STORED AS PARQUET
  32. > PARTITIONED BY (year INT);
  33. Fetched 0 row(s) in 0.10s

Next, we copy all the rows from the original table into this new one with an INSERT statement. (We edited the CREATE TABLE statement to make an INSERT statement with the column names in the same order.) The only change is to add a PARTITION(year) clause, and move the YEAR column to the very end of the SELECT list of the INSERT statement. Specifying PARTITION(year), rather than a fixed value such as PARTITION(year=2000), means that Impala figures out the partition value for each row based on the value of the very last column in the SELECT list. This is the first SQL statement that legitimately takes any substantial time, because the rows from different years are shuffled around the cluster; the rows that go into each partition are collected on one node, before being written to one or more new data files.

  1. [localhost:21000] > INSERT INTO airline_data.airlines
  2. > PARTITION (year)
  3. > SELECT
  4. > month,
  5. > day,
  6. > dayofweek,
  7. > dep_time,
  8. > crs_dep_time,
  9. > arr_time,
  10. > crs_arr_time,
  11. > carrier,
  12. > flight_num,
  13. > actual_elapsed_time,
  14. > crs_elapsed_time,
  15. > airtime,
  16. > arrdelay,
  17. > depdelay,
  18. > origin,
  19. > dest,
  20. > distance,
  21. > taxi_in,
  22. > taxi_out,
  23. > cancelled,
  24. > cancellation_code,
  25. > diverted,
  26. > carrier_delay,
  27. > weather_delay,
  28. > nas_delay,
  29. > security_delay,
  30. > late_aircraft_delay,
  31. > year
  32. > FROM airline_data.airlines_external;
  33. Inserted 123534969 row(s) in 202.70s

Once partitioning or join queries come into play, it’s important to have statistics that Impala can use to optimize queries on the corresponding tables. The COMPUTE INCREMENTAL STATS statement is the way to collect statistics for partitioned tables. Then the SHOW TABLE STATS statement confirms that the statistics are in place for each partition, and also illustrates how many files and how much raw data is in each partition.

  1. [localhost:21000] > compute incremental stats airlines;
  2. +-------------------------------------------+
  3. | summary |
  4. +-------------------------------------------+
  5. | Updated 22 partition(s) and 27 column(s). |
  6. +-------------------------------------------+
  7. [localhost:21000] > show table stats airlines;
  8. +-------+-----------+--------+----------+--------------+------------+---------+-------------------+
  9. | year | #Rows | #Files | Size | Bytes Cached | Cache Repl | Format | Incremental stats |
  10. +-------+-----------+--------+----------+--------------+------------+---------+-----
  11. | 1987 | 1311826 | 1 | 9.32MB | NOT CACHED | NOT CACHED | PARQUET | true
  12. | 1988 | 5202096 | 1 | 37.04MB | NOT CACHED | NOT CACHED | PARQUET | true
  13. | 1989 | 5041200 | 1 | 36.25MB | NOT CACHED | NOT CACHED | PARQUET | true
  14. | 1990 | 5270893 | 1 | 38.39MB | NOT CACHED | NOT CACHED | PARQUET | true
  15. | 1991 | 5076925 | 1 | 37.23MB | NOT CACHED | NOT CACHED | PARQUET | true
  16. | 1992 | 5092157 | 1 | 36.85MB | NOT CACHED | NOT CACHED | PARQUET | true
  17. | 1993 | 5070501 | 1 | 37.16MB | NOT CACHED | NOT CACHED | PARQUET | true
  18. | 1994 | 5180048 | 1 | 38.31MB | NOT CACHED | NOT CACHED | PARQUET | true
  19. | 1995 | 5327435 | 1 | 53.14MB | NOT CACHED | NOT CACHED | PARQUET | true
  20. | 1996 | 5351983 | 1 | 53.64MB | NOT CACHED | NOT CACHED | PARQUET | true
  21. | 1997 | 5411843 | 1 | 54.41MB | NOT CACHED | NOT CACHED | PARQUET | true
  22. | 1998 | 5384721 | 1 | 54.01MB | NOT CACHED | NOT CACHED | PARQUET | true
  23. | 1999 | 5527884 | 1 | 56.32MB | NOT CACHED | NOT CACHED | PARQUET | true
  24. | 2000 | 5683047 | 1 | 58.15MB | NOT CACHED | NOT CACHED | PARQUET | true
  25. | 2001 | 5967780 | 1 | 60.65MB | NOT CACHED | NOT CACHED | PARQUET | true
  26. | 2002 | 5271359 | 1 | 57.99MB | NOT CACHED | NOT CACHED | PARQUET | true
  27. | 2003 | 6488540 | 1 | 81.33MB | NOT CACHED | NOT CACHED | PARQUET | true
  28. | 2004 | 7129270 | 1 | 103.19MB | NOT CACHED | NOT CACHED | PARQUET | true
  29. | 2005 | 7140596 | 1 | 102.61MB | NOT CACHED | NOT CACHED | PARQUET | true
  30. | 2006 | 7141922 | 1 | 106.03MB | NOT CACHED | NOT CACHED | PARQUET | true
  31. | 2007 | 7453215 | 1 | 112.15MB | NOT CACHED | NOT CACHED | PARQUET | true
  32. | 2008 | 7009728 | 1 | 105.76MB | NOT CACHED | NOT CACHED | PARQUET | true
  33. | Total | 123534969 | 22 | 1.30GB | 0B | | |
  34. +-------+-----------+--------+----------+--------------+------------+---------+-----

At this point, we go through a quick thought process to sanity check the partitioning we did. All the partitions have exactly one file, which is on the low side. A query that includes a clause WHERE year=2004 will only read a single data block; that data block will be read and processed by a single data node; therefore, for a query targeting a single year, all the other nodes in the cluster will sit idle while all the work happens on a single machine. It’s even possible that by chance (depending on HDFS replication factor and the way data blocks are distributed across the cluster), that multiple year partitions selected by a filter such as WHERE year BETWEEN 1999 AND 2001 could all be read and processed by the same data node. The more data files each partition has, the more parallelism you can get and the less probability of “hotspots” occurring on particular nodes, therefore a bigger performance boost by having a big cluster.

However, the more data files, the less data goes in each one. The overhead of dividing the work in a parallel query might not be worth it if each node is only reading a few megabytes. 50 or 100 megabytes is a decent size for a Parquet data block; 9 or 37 megabytes is on the small side. Which is to say, the data distribution we ended up with based on this partitioning scheme is on the borderline between sensible (reasonably large files) and suboptimal (few files in each partition). The way to see how well it works in practice is to run the same queries against the original flat table and the new partitioned table, and compare times.

Spoiler: in this case, with my particular 4-node cluster with its specific distribution of data blocks and my particular exploratory queries, queries against the partitioned table do consistently run faster than the same queries against the unpartitioned table. But I could not be sure that would be the case without some real measurements. Here are some queries I ran to draw that conclusion, first against AIRLINES_EXTERNAL (no partitioning), then against AIRLINES (partitioned by year). The AIRLINES queries are consistently faster. Changing the volume of data, changing the size of the cluster, running queries that did or didn’t refer to the partition key columns, or other factors could change the results to favor one table layout or the other.

Note: If you find the volume of each partition is only in the low tens of megabytes, consider lowering the granularity of partitioning. For example, instead of partitioning by year, month, and day, partition by year and month or even just by year. The ideal layout to distribute work efficiently in a parallel query is many tens or even hundreds of megabytes per Parquet file, and the number of Parquet files in each partition somewhat higher than the number of data nodes.

  1. [localhost:21000] > select sum(airtime) from airlines_external;
  2. +--------------+
  3. | sum(airtime) |
  4. +--------------+
  5. | 8662859484 |
  6. +--------------+
  7. Fetched 1 row(s) in 2.02s
  8. [localhost:21000] > select sum(airtime) from airlines;
  9. +--------------+
  10. | sum(airtime) |
  11. +--------------+
  12. | 8662859484 |
  13. +--------------+
  14. Fetched 1 row(s) in 1.21s
  15. [localhost:21000] > select sum(airtime) from airlines_external where year = 2005;
  16. +--------------+
  17. | sum(airtime) |
  18. +--------------+
  19. | 708204026 |
  20. +--------------+
  21. Fetched 1 row(s) in 2.61s
  22. [localhost:21000] > select sum(airtime) from airlines where year = 2005;
  23. +--------------+
  24. | sum(airtime) |
  25. +--------------+
  26. | 708204026 |
  27. +--------------+
  28. Fetched 1 row(s) in 1.19s
  29. [localhost:21000] > select sum(airtime) from airlines_external where dayofweek = 1;
  30. +--------------+
  31. | sum(airtime) |
  32. +--------------+
  33. | 1264945051 |
  34. +--------------+
  35. Fetched 1 row(s) in 2.82s
  36. [localhost:21000] > select sum(airtime) from airlines where dayofweek = 1;
  37. +--------------+
  38. | sum(airtime) |
  39. +--------------+
  40. | 1264945051 |
  41. +--------------+
  42. Fetched 1 row(s) in 1.61s

Now we can finally do some serious analysis with this data set that, remember, a few minutes ago all we had were some raw data files and we didn’t even know what columns they contained. Let’s see whether the “air time” of a flight tends to be different depending on the day of the week. We can see that the average is a little higher on day number 6; perhaps Saturday is a busy flying day and planes have to circle for longer at the destination airport before landing.

  1. [localhost:21000] > select dayofweek, avg(airtime) from airlines
  2. > group by dayofweek order by dayofweek;
  3. +-----------+-------------------+
  4. | dayofweek | avg(airtime) |
  5. +-----------+-------------------+
  6. | 1 | 102.1560425016671 |
  7. | 2 | 102.1582931538807 |
  8. | 3 | 102.2170009256653 |
  9. | 4 | 102.37477661846 |
  10. | 5 | 102.2697358763511 |
  11. | 6 | 105.3627448363705 |
  12. | 7 | 103.4144351202054 |
  13. +-----------+-------------------+
  14. Fetched 7 row(s) in 2.25s

To see if the apparent trend holds up over time, let’s do the same breakdown by day of week, but also split up by year. Now we can see that day number 6 consistently has a higher average air time in each year. We can also see that the average air time increased over time across the board. And the presence of NULL for this column in years 1987 to 1994 shows that queries involving this column need to be restricted to a date range of 1995 and higher.

  1. [localhost:21000] > select year, dayofweek, avg(airtime) from airlines
  2. > group by year, dayofweek order by year desc, dayofweek;
  3. +------+-----------+-------------------+
  4. | year | dayofweek | avg(airtime) |
  5. +------+-----------+-------------------+
  6. | 2008 | 1 | 103.1821651651355 |
  7. | 2008 | 2 | 103.2149301386094 |
  8. | 2008 | 3 | 103.0585076622796 |
  9. | 2008 | 4 | 103.4671383539038 |
  10. | 2008 | 5 | 103.5575385182659 |
  11. | 2008 | 6 | 107.4006306562128 |
  12. | 2008 | 7 | 104.8648851041755 |
  13. | 2007 | 1 | 102.2196114337825 |
  14. | 2007 | 2 | 101.9317791906348 |
  15. | 2007 | 3 | 102.0964767689043 |
  16. | 2007 | 4 | 102.6215927201686 |
  17. | 2007 | 5 | 102.4289399000661 |
  18. | 2007 | 6 | 105.1477448215756 |
  19. | 2007 | 7 | 103.6305945644095 |
  20. ...
  21. | 1996 | 1 | 99.33860750862108 |
  22. | 1996 | 2 | 99.54225446396656 |
  23. | 1996 | 3 | 99.41129336113134 |
  24. | 1996 | 4 | 99.5110373340348 |
  25. | 1996 | 5 | 99.22120745027595 |
  26. | 1996 | 6 | 101.1717447111921 |
  27. | 1996 | 7 | 99.95410136133704 |
  28. | 1995 | 1 | 96.93779698300494 |
  29. | 1995 | 2 | 96.93458674589712 |
  30. | 1995 | 3 | 97.00972311337051 |
  31. | 1995 | 4 | 96.90843832024412 |
  32. | 1995 | 5 | 96.78382115425562 |
  33. | 1995 | 6 | 98.70872826057003 |
  34. | 1995 | 7 | 97.85570478374616 |
  35. | 1994 | 1 | NULL |
  36. | 1994 | 2 | NULL |
  37. | 1994 | 3 | NULL |
  38. ...
  39. | 1987 | 5 | NULL |
  40. | 1987 | 6 | NULL |
  41. | 1987 | 7 | NULL |
  42. +------+-----------+-------------------+