cta

Get Started

cloud

Ready to Get Started?

Download sandbox

How can we help you?

closeClose button

Hadoop Tutorial – Getting Started with HDP

Introduction

Hello World is often used by developers to familiarize themselves with new concepts by building a simple program. This tutorial aims to achieve a similar purpose by getting practitioners started with Hadoop and HDP. We will use an Internet of Things (IoT) use case to build your first HDP application.

This tutorial describes how to refine data for a Trucking IoT  Data Discovery (aka IoT Discovery) use case using the Hortonworks Data Platform. The IoT Discovery use cases involves vehicles, devices and people moving across a map or similar surface. Your analysis is targeted to linking location information with your analytic data.

For our tutorial we are looking at a use case where we have a truck fleet. Each truck has been equipped to log location and event data. These events are streamed back to a datacenter where we will be processing the data.  The company wants to use this data to better understand risk.

Here is the video of Analyzing Geolocation Data to show you what you’ll be doing in this tutorial.

Pre-Requisites:

Tutorial Overview

In this tutorial, we will provide the collected geolocation and truck data. We will import this data into HDFS and build derived tables in Hive. Then we will process the data using Pig, Hive and Spark. The processed data is then visualized using Apache Zeppelin.

To refine and analyze Geolocation data, we will:

  • Review some Hadoop Fundamentals
  • Download and extract the Geolocation data files.
  • Load the captured data into the Hortonworks Sandbox.
  • Run Hive, Pig and Spark scripts that compute truck mileage and driver risk factor.
  • Visualize the geolocation data using Zeppelin.

Goals of the Tutorial

The goal of this tutorial is that you get familiar with the basics of following:

  • Hadoop and HDP
  • Ambari File User Views and HDFS
  • Ambari Hive User Views and Apache Hive
  • Ambari Pig User Views and Apache Pig
  • Apache Spark
  • Data Visualization with Zeppelin (Optional)

Outline

  1. Introduction
  2. Pre-Requisites
    1. Data Set Used: Geolocation.zip
    2. Latest Hortonworks Sandbox Version
    3. Learning the Ropes of the Hortonworks Sandbox – Become familiar with your Sandbox and Ambari.
  3. Tutorial Overview
  4. Goals of the Tutorial (outcomes)
  5. Hadoop Data Platform Concepts (New to Hadoop or HDP- Refer following)
    1. Apache Hadoop and HDP (5 Pillars)
    2. Apache Hadoop Distributed File System (HDFS)
    3. Apache YARN
    4. Apache MapReduce
    5. Apache Hive
    6. Apache Pig
  6. Get Started with HDP Labs
    1. Lab 1: Loading Sensor Data into HDFS
    2. Lab 2: Data Manipulation with Hive (Ambari User Views)
    3. Lab 3: Use Pig to compute Driver Risk Factor
    4. Lab 4: Use Apache Spark to compute Driver Risk Factor
    5. Lab 5: Optional Visualization and Reporting with Zeppelin
  7. Next Steps/Try These
    1. Practitioner Journey-  As a Hadoop Practitioner you can adopt following learning paths
    2. Case Studies – Learn how Hadoop is being used by various industries.
  8. References and Resources
    1. Hadoop – The Definitive Guide by O`Reilly
    2. Hadoop for Dummies
    3. Hadoop Crash Course slides-Hadoop Summit 2015
    4. Hadoop Crash Course Workshop- Hadoop Summit 2015

Concepts

In this tutorial, we will explore important concepts that will strengthen your foundation in the Hortonworks Data Platform (HDP). Apache Hadoop is a layered structure to process and store massive amounts of data. In our case, ApacheTM Hadoop will be recognized as an enterprise solution in the form of HDP. At the base of HDP exists our data storage environment known as the Hadoop Distributed File System. When data files are accessed by Hive, Pig or another coding language, YARN is the Data Operating System that enables them to analyze, manipulate or process that data. HDP includes various components that open new opportunities and efficiencies in healthcare, finance, insurance and other industries that impact people.

Pre-Requisites

Outline

  1. Concept: Hadoop & HDP
  2. Concept: HDFS
  3. Concept: MapReduce & YARN
  4. Concept: Hive and Pig

1st Concept: Hadoop & HDP

1.1 Introduction

In this module you will learn about ApacheTM Hadoop® and what makes it scale to large data sets. We will also talk about various components of the Hadoop ecosystem that make Apache Hadoop enterprise ready in the form of Hortonworks Data Platform (HDP) distribution. This module discusses Apache Hadoop and its capabilities as a data platform. The core of Hadoop and its surrounding ecosystem solution vendors provide enterprise requirements to integrate alongside Data Warehouses and other enterprise data systems. These are steps towards the implementation of a modern data architecture, and towards delivering an enterprise ‘Data Lake’

1.2 Goals of this module

  • Understanding Hadoop.
  • Understanding five pillars of HDP
  • Understanding HDP components and their purpose.

1.3 Apache Hadoop

Apache Hadoop is an open source framework for distributed storage and processing of large sets of data on commodity hardware. Hadoop enables businesses to quickly gain insight from massive amounts of structured and unstructured data. Numerous Apache Software Foundation projects make up the services required by an enterprise to deploy, integrate and work with Hadoop. Refer to the blog reference below for more information on Hadoop.

The base Apache Hadoop framework is composed of the following modules:

  • Hadoop Common – contains libraries and utilities needed by other Hadoop modules.
  • Hadoop Distributed File System (HDFS) – a distributed file-system that stores data on commodity machines, providing very high aggregate bandwidth across the cluster.
  • Hadoop YARN – a resource-management platform responsible for managing computing resources in clusters and using them for scheduling of users’ applications.
  • Hadoop MapReduce – a programming model for large scale data processing.

Each project has been developed to deliver an explicit function and each has its own community of developers and individual release cycles. There are five pillars to Hadoop that make it enterprise ready:

  1. Data Management– Store and process vast quantities of data in a storage layer that scales linearly. Hadoop Distributed File System (HDFS) is the core technology for the efficient scale out storage layer, and is designed to run across low-cost commodity hardware. Apache Hadoop YARN is the pre-requisite for Enterprise Hadoop as it provides the resource management and pluggable architecture for enabling a wide variety of data access methods to operate on data stored in Hadoop with predictable performance and service levels.
    1. Apache Hadoop YARN– Part of the core Hadoop project, YARN is a next-generation framework for  Hadoop data processing extending MapReduce capabilities by supporting non-MapReduce workloads associated with other programming models.
    2. HDFS– Hadoop Distributed File System (HDFS) is a Java-based file system that provides scalable and reliable data storage that is designed to span large clusters of commodity servers.
  2. Data Access– Interact with your data in a wide variety of ways – from batch to real-time. Apache       Hive is the most widely adopted data access technology, though there are many specialized engines. For instance, Apache Pig provides scripting capabilities, Apache Storm offers real-time processing,     Apache HBase offers columnar NoSQL storage and Apache Accumulo offers cell-level access           control. All of these engines can work across one set of data and resources thanks to YARN and       intermediate engines such as Apache Tez for interactive access and Apache Slider for long-running   applications. YARN also provides flexibility for new and emerging data access methods, such as         Apache Solr for search and programming frameworks such as Cascading.
    1. Apache Hive– Built on the MapReduce framework, Hive is a data warehouse that enables easy data summarization and ad-hoc queries via an SQL-like interface for large datasets stored in HDFS.
    2. Apache Pig– A platform for processing and analyzing large data sets. Pig consists of a high-level language (Pig Latin) for expressing data analysis programs paired with the MapReduce framework for processing these programs.
    3. MapReduce– MapReduce is a framework for writing applications that process large amounts of structured and unstructured data in parallel across a cluster of thousands of machines, in a reliable and fault-tolerant manner.
    4. Apache Spark– Spark is ideal for in-memory data processing. It allows data scientists to implement fast, iterative algorithms for advanced analytics such as clustering and classification of datasets.
    5. Apache Storm– Storm is a distributed real-time computation system for processing fast, large streams of data adding reliable real-time data processing capabilities to Apache Hadoop® 2.x
    6. Apache HBase– A column-oriented NoSQL data storage system that provides random real-time read/write access to big data for user applications.
    7. Apache Tez– Tez generalizes the MapReduce paradigm to a more powerful framework for executing a complex DAG (directed acyclic graph) of tasks for near real-time big data processing.
    8. Apache Kafka– Kafka is a fast and scalable publish-subscribe messaging system that is often used in place of traditional message brokers because of its higher throughput, replication, and fault tolerance.
    9. Apache HCatalog– A table and metadata management service that provides a centralized way for data processing systems to understand the structure and location of the data stored within Apache Hadoop.
    10. Apache Slider– A framework for deployment of long-running data access applications in Hadoop. Slider leverages YARN’s resource management capabilities to deploy those applications, to manage their lifecycles and scale them up or down.
    11. Apache Solr– Solr is the open source platform for searches of data stored in Hadoop. Solr enables powerful full-text search and near real-time indexing on many of the world’s largest Internet sites.
    12. Apache Mahout– Mahout provides scalable machine learning algorithms for Hadoop which aids with data science for clustering, classification and batch based collaborative filtering.
    13. Apache Accumulo– Accumulo is a high performance data storage and retrieval system with cell-level access control. It is a scalable implementation of Google’s Big Table design that works on top of Apache Hadoop and Apache ZooKeeper.
  3. Data Governance and Integration– Quickly and easily load data, and manage   according to           policy.Apache Falcon provides policy-based workflows for data governance, while Apache Flume and Sqoop enable easy data ingestion, as do the NFS and WebHDFS interfaces to HDFS.
    1. Apache Falcon– Falcon is a data management framework for simplifying data lifecycle management and processing pipelines on Apache Hadoop®. It enables users to orchestrate data motion, pipeline processing,disaster recovery, and data retention workflows.
    2. Apache Flume– Flume allows you to efficiently aggregate and move large amounts of log data from many different sources to Hadoop.
    3. Apache Sqoop– Sqoop is a tool that speeds and eases movement of data in and out of Hadoop. It provides a reliable parallel load for various, popular enterprise data sources.
  4. Security– Address requirements of Authentication, Authorization, Accounting and Data Protection. Security is provided at every layer of the Hadoop stack from HDFS and YARN to Hive and the other Data Access components on up through the entire perimeter of the cluster via Apache Knox.
    1. Apache Knox– The Knox Gateway (“Knox”) provides a single point of authentication and access for Apache Hadoop services in a cluster. The goal of the project is to simplify Hadoop security for users who access the cluster data and execute jobs, and for operators who control access to the cluster.
    2. Apache Ranger– Apache Ranger delivers a comprehensive approach to security for a Hadoop cluster. It provides central security policy administration across the core enterprise security requirements of authorization, accounting and data protection.
  5. Operations–  Provision, manage, monitor and operate Hadoop clusters at scale.
    1. Apache Ambari– An open source installation lifecycle management, administration and monitoring system for Apache Hadoop clusters.
    2. Apache Oozie– Oozie Java Web application used to schedule Apache Hadoop jobs. Oozie combines multiple jobs sequentially into one logical unit of work.
    3. Apache ZooKeeper– A highly available system for coordinating distributed processes. Distributed applications use ZooKeeper to store and mediate updates to important configuration information.

Apache Hadoop can be useful across a range of use cases spanning virtually every vertical industry. It is becoming popular anywhere that you need to store, process, and analyze large volumes of data. Examples include digital marketing automation, fraud detection and prevention, social network and relationship analysis, predictive modeling for new drugs, retail in-store behavior analysis, and mobile device location-based marketing.  To learn more about Apache Hadoop, watch the following introduction:

1.4 Hortonworks Data Platform (HDP)

Hortonworks Data Platform (HDP) is a packaged software Hadoop distribution that aims to ease deployment and management of Hadoop clusters. Compared with simply downloading the various Apache code bases and trying to run them together a system, HDP greatly simplifies the use of Hadoop. Architected, developed, and built completely in the open, HDP provides an enterprise ready data platform that enables organizations to adopt a Modern Data Architecture.

With YARN as its architectural center it provides a data platform for multi-workload data processing across an array of processing methods – from batch through interactive to real-time, supported by key capabilities required of an enterprise data platform — spanning Governance, Security and Operations.

The Hortonworks Sandbox is a single node implementation of HDP. It is packaged as a virtual machine to make evaluation and experimentation with HDP fast and easy. The tutorials and features in the Sandbox are oriented towards exploring how HDP can help you solve your business big data problems. The Sandbox tutorials will walk you through how to bring some sample data into HDP and how to manipulate it using the tools built into HDP. The idea is to show you how you can get started and show you how to accomplish tasks in HDP. HDP is free to download and use in your enterprise and you can download it here: Hortonworks Data Platform

1.5 Suggested Readings

Hadoop Blogs:

2nd Concept: HDFS

2.1 Introduction

A single physical machine gets saturated with its storage capacity as data grows. With this growth comes the impending need to partition your data across separate machines. This type of File system that manages storage of data across a network of machines is called a Distributed File System. HDFS is a core component of Apache Hadoop and is designed to store large files with streaming data access patterns, running on clusters of commodity hardware. With Hortonworks Data Platform HDP 2.2, HDFS is now expanded to support heterogeneous storage  media within the HDFS cluster.

2.2 Goals of this module

  • Understanding HDFS architecture
  • Understanding Hortonworks Sandbox Amabri File User View

2.3 Hadoop Distributed File System

HDFS is a distributed file system that is designed for storing large data files. HDFS is a Java-based file system that provides scalable and reliable data storage, and it was designed to span large clusters of commodity servers. HDFS has demonstrated production scalability of up to 200 PB of storage and a single cluster of 4500 servers, supporting close to a billion files and blocks. HDFS is a scalable, fault-tolerant, distributed storage system that works closely with a wide variety of concurrent data access applications, coordinated by YARN. HDFS will “just work” under a variety of physical and systemic circumstances. By distributing storage and computation across many servers, the combined storage resource can grow linearly with demand while remaining economical at every amount of storage.

HDSF_1

An HDFS cluster is comprised of a NameNode, which manages the cluster metadata, and DataNodes that store the data. Files and directories are represented on the NameNode by inodes. Inodes record attributes like permissions, modification and access times, or namespace and disk space quotas.

The file content is split into large blocks (typically 128 megabytes), and each block of the file is independently replicated at multiple DataNodes. The blocks are stored on the local file system on the DataNodes.

The Namenode actively monitors the number of replicas of a block. When a replica of a block is lost due to a DataNode failure or disk failure, the NameNode creates another replica of the block. The NameNode maintains the namespace tree and the mapping of blocks to DataNodes, holding the entire namespace image in RAM.

The NameNode does not directly send requests to DataNodes. It sends instructions to the DataNodes by replying to heartbeats sent by those DataNodes. The instructions include commands to:

  • replicate blocks to other nodes,
  • remove local block replicas,
  • re-register and send an immediate block report, or
  • shut down the node.

HDFS_2

With the next generation HDFS data architecture that comes with HDP 2.4, HDFS has evolved to provide automated failure with a hot standby, with full stack resiliency. The video provides more clarity on HDFS.

2.3.1 Ambari Files User View on Hortonworks Sandbox

Ambari Files User View

HDFS_3

Ambari Files User View provides a user friendly interface to upload, store and move data. Underlying all components in Hadoop is the Hadoop Distributed File System(HDFS™).  This is the foundation of the Hadoop cluster. The HDFS file system manages how the datasets are stored in the Hadoop cluster. It is responsible for distributing the data across the datanodes, managing replication for redundancy and administrative tasks like adding, removing and recovery of data nodes.

2.4 Suggested Readings

Hadoop 2.0 Blogs:

HDFS Blogs:

3rd Concept: MapReduce & YARN

3.1 Introduction

Cluster computing faces several challenges such as how to store data persistently and keep it available if nodes fail or how to deal with node failures during a long running computation. Also there is network bottleneck which delays the time of processing data. MapReduce offers a solution by bring computation close to data thereby minimizing data movement. It is a simple programming model designed to process large volumes of data in parallel by dividing the job into a set of independent tasks.

The biggest limitation with MapReduce programming is that map and reduce jobs are not stateless. This means that Reduce jobs have to wait for map jobs to be completed first. This limits maximum parallelism and therefore YARN was born as a generic resource management and distributed application framework.

3.2 Goals of the Module

  • Understanding Map and Reduce jobs.
  • Understanding YARN

3.3 Apache MapReduce

MapReduce is the key algorithm that the Hadoop data processing engine uses to distribute work around a cluster. A MapReduce job splits a large data set into independent chunks and organizes them into key, value pairs for parallel processing. This parallel processing improves the speed and reliability of the cluster, returning solutions more quickly and with greater reliability.

The Map function divides the input into ranges by the InputFormat and creates a map task for each range in the input. The JobTracker distributes those tasks to the worker nodes. The output of each map task is partitioned into a group of key-value pairs for each reduce.

  • map(key1,value) -> list<key2,value2>

The Reduce function then collects the various results and combines them to answer the larger problem that the master node needs to solve. Each reduce pulls the relevant partition from the machines where the maps executed, then writes its output back into HDFS. Thus, the reduce is able to collect the data from all of the maps for the keys and combine them to solve the problem.

  • reduce(key2, list<value2>) -> list<value3>

The current Apache Hadoop MapReduce System is composed of the JobTracker, which is the master, and the per-node slaves called TaskTrackers. The JobTracker is responsible for resource management (managing the worker nodes i.e. TaskTrackers), tracking resource consumption/availability and also job life-cycle management (scheduling individual tasks of the job, tracking progress, providing fault-tolerance for tasks etc).

The TaskTracker has simple responsibilities – launch/teardown tasks on orders from the JobTracker and provide task-status information to the JobTracker periodically.

MapR_1

The Apache Hadoop projects provide a series of tools designed to solve big data problems. The Hadoop cluster implements a parallel computing cluster using inexpensive commodity hardware. The cluster is partitioned across many servers to provide a near linear scalability. The philosophy of the cluster design is to bring the computing to the data. So each datanode will hold part of the overall data and be able to process the data that it holds. The overall framework for the processing software is called MapReduce. Here’s a short video introduction to MapReduce:

MapR_2

3.4 Apache YARN (Yet Another Resource Negotiator)

Hadoop HDFS is the data storage layer for Hadoop and MapReduce was the data-processing layer in Hadoop 1x. However, the MapReduce algorithm, by itself, isn’t sufficient for the very wide variety of use-cases we see Hadoop being employed to solve. Hadoop 2.0 presents YARN, as a generic resource-management and distributed application framework, whereby, one can implement multiple data processing applications customized for the task at hand. The fundamental idea of YARN is to split up the two major responsibilities of the JobTracker i.e. resource management and job scheduling/monitoring, into separate daemons: a global ResourceManager and per-application ApplicationMaster (AM).

The ResourceManager and per-node slave, the NodeManager (NM), form the new, and generic, system for managing applications in a distributed manner.

The ResourceManager is the ultimate authority that arbitrates resources among all the applications in the system. The per-application ApplicationMaster is, in effect, a framework specific entity and is tasked with negotiating resources from the ResourceManager and working with the NodeManager(s) to execute and monitor the component tasks.

ResourceManager has a pluggable Scheduler, which is responsible for allocating resources to the various running applications subject to familiar constraints of capacities, queues etc. The Scheduler is a pure scheduler in the sense that it performs no monitoring or tracking of status for the application, offering no guarantees on restarting failed tasks either due to application failure or hardware failures. The Scheduler performs its scheduling function based on the resource requirements of the applications; it does so based on the abstract notion of a **Resource Container **which incorporates resource elements such as memory, CPU, disk, network etc.

NodeManager is the per-machine slave, which is responsible for launching the applications’ containers, monitoring their resource usage (CPU, memory, disk, network) and reporting the same to the ResourceManager.

The per-application ApplicationMaster has the responsibility of negotiating appropriate resource containers from the Scheduler, tracking their status and monitoring for progress. From the system perspective, the ApplicationMaster itself runs as a normal container.

Here is an architectural view of YARN:

MapR_3

One of the crucial implementation details for MapReduce within the new YARN system that I’d like to point out is that we have reused the existing MapReduce framework without any major surgery. This was very important to ensure compatibility for existing MapReduce applications and users. Here is a short video introduction for YARN.

3.5 Suggested Readings

Hadoop 2.0 Blogs:
Hadoop 2.7.0 Blog
Understanding Hadoop 2.0

YARN Blogs:
YARN series-1
YARN series-2

Slider Blogs:
Announcing Apache Slider 0.60.0
Onboarding Long Running Services to Apache Hadoop YARN Using Apache Slider
Build YARN Apps on Hadoop with Apache Slider: Technical Preview Now Available

Capacity Scheduler Blogs:
Understanding Apache Hadoop’s Capacity Scheduler
Configuring YARN Capacity Scheduler with Ambari
Multi-Tenancy in HDP 2.0: Capacity Scheduler and YARN
Better SLAs via Resource-preemption in YARN’s Capacity Scheduler

4th Concept: Hive and Pig

4.1 Introduction: Apache Hive

Hive is an SQL like query language that enables those analysts familiar with SQL to run queries on large volumes of data.  Hive has three main functions: data summarization, query and analysis. Hive provides tools that enable easy data extraction, transformation and loading (ETL).

4.2 Goals of the module

  • Understanding Apache Hive
  • Understanding Apache Tez
  • Understanding Ambari Hiver User Views on Hortonworks Sandbox

4.3 Apache Hive

Data analysts use Hive to explore, structure and analyze that data, then turn it into business insights. Hive implements a dialect of SQL (Hive QL) that focuses on analytics and presents a rich set of SQL semantics including OLAP functions, sub-queries, common table expressions and more. Hive allows SQL developers or users with SQL tools to easily query, analyze and process data stored in Hadoop.Hive also allows programmers familiar with the MapReduce framework to plug in their custom mappers and reducers to perform more sophisticated analysis that may not be supported by the built-in capabilities of the language.

Hive users have a choice of 3 runtimes when executing SQL queries. Users can choose between Apache Hadoop MapReduce, Apache Tez or Apache Spark frameworks as their execution backend.

Here are some advantageous characteristics of Hive for enterprise SQL in Hadoop:

Feature Description
Familiar Query data with a SQL-based language
Fast Interactive response times, even over huge datasets
Scalable and Extensible As data variety and volume grows, more commodity machines can be added, without a corresponding reduction in performance

4.3.1 How Hive Works

The tables in Hive are similar to tables in a relational database, and data units are organized in a taxonomy from larger to more granular units. Databases are comprised of tables, which are made up of partitions. Data can be accessed via a simple query language and Hive supports overwriting or appending data.

Within a particular database, data in the tables is serialized and each table has a corresponding Hadoop Distributed File System (HDFS) directory. Each table can be sub-divided into partitions that determine how data is distributed within sub-directories of the table directory. Data within partitions can be further broken down into buckets.

4.3.2 Components of Hive

  • HCatalog is a component of Hive. It is a table and storage management layer for Hadoop that enables users with different data processing tools — including Pig and MapReduce — to more easily read and write data on the grid. HCatalog holds a set of files paths and metadata about data in a Hadoop cluster. This allows scripts, MapReduce and Tez, jobs to be decoupled from data location and metadata like the schema. Additionally, since HCatalog also supports tools like Hive and Pig, the location and metadata can be shared between tools. Using the open APIs of HCatalog external tools that want to integrate, such as Teradata Aster, can also use leverage file path location and metadata in HCatalog.

At one point HCatalog was its own Apache project. However, in March, 2013, HCatalog’s project merged with Hive.  HCatalog is currently released as part of Hive.

  • WebHCat provides a service that you can use to run Hadoop MapReduce (or YARN), Pig, Hive jobs or perform Hive metadata operations using an HTTP (REST style) interface.

Here is a short video introduction on Hive:

4.3.3 Apache Tez

Apache Tez is an extensible framework for building high performance batch and interactive data processing applications, coordinated by YARN in Apache Hadoop. Tez improves the MapReduce paradigm by dramatically improving its speed, while maintaining MapReduce’s ability to scale to petabytes of data. Important Hadoop ecosystem projects like Apache Hive and Apache Pig use Apache Tez, as do a growing number of third party data access applications developed for the broader Hadoop ecosystem.

Apache Tez provides a developer API and framework to write native YARN applications that bridge the spectrum of interactive and batch workloads. It allows those data access applications to work with petabytes of data over thousands nodes. The Apache Tez component library allows developers to create Hadoop applications that integrate natively with Apache Hadoop YARN and perform well within mixed workload clusters.

Since Tez is extensible and embeddable, it provides the fit-to-purpose freedom to express highly optimized data processing applications, giving them an advantage over end-user-facing engines such as MapReduce and Apache Spark. Tez also offers a customizable execution architecture that allows users to express complex computations as dataflow graphs, permitting dynamic performance optimizations based on real information about the data and the resources required to process it.

Hive_1

Hive_2

Hive_3

Here is a short video introduction on Tez.

4.3.4 Stinger and Stinger.next

The Stinger Initiative was started to enable Hive to support an even broader range of use cases at truly Big Data scale: bringing it beyond its Batch roots to support interactive queries – all with a common SQL access layer.

Stinger.next is a continuation of this initiative focused on even further enhancing the speed, scale and breadth of SQL support to enable truly real-time access in Hive while also bringing support for transactional capabilities.  And just as the original Stinger initiative did, this will be addressed through a familiar three-phase delivery schedule and developed completely in the open Apache Hive community.

Hive_4

4.3.5 Ambari Hive User Views on Hortonworks Sandbox

To make it easy to interact with Hive we use a tool in the Hortonworks Sandbox called the Ambari Hive User View.   Ambari Hive User View provides an interactive interface to Hive.   We can create, edit, save and run queries, and have Hive evaluate them for us using a series of MapReduce jobs or Tez jobs.

Let’s now open the Ambari Hive User View and get introduced to the environment, go to the Ambari User VIew icon and select Hive :

Screen Shot 2016-02-17 at 7.10.18 PM

Ambari Hive User View

Hive_6

Now let’s take a closer look at the SQL editing capabilities in the User View:

  1. There are five tabs to interact with SQL:
    1. Query: This is the interface shown above and the primary interface to write, edit and execute new SQL statements
    2. Saved Queries: You can save your favorite queries and quickly have access to them to rerun or edit.
    3. History: This allows you to look at past queries or currently running queries to view, edit and rerun.  It also allows you to see all SQL queries you have authority to view.  For example, if you are an operator and an analyst needs help with a query, then the Hadoop operator can use the History feature to see the query that was sent from the reporting tool.
    4. UDFs:  Allows you to define UDF interfaces and associated classes so you can access them from the SQL editor.
    5. Upload Table: Allows you to upload your hive query tables to your preferred database and appears instantly in the Query Editor for execution.
  2. Database Explorer:  The Database Explorer helps you navigate your database objects.  You can either search for a database object in the Search tables dialog box, or you can navigate through Database -> Table -> Columns in the navigation pane.
  3. The principle pane to write and edit SQL statements. This editor includes content assist via CTRL + Space to help you build queries. Content assist helps you with SQL syntax and table objects.
  4. Once you have created your SQL statement you have 4 options:
    1. Execute: This runs the SQL statement.
    2. Explain: This provides you a visual plan, from the Hive optimizer, of how the SQL statement will be executed.
    3. Save as:  Allows you to persist your queries into your list of saved queries.
    4. Kill Session: Terminates the SQL statement.
  5. When the query is executed you can see the Logs or the actual query results.
    1. Logs: When the query is executed you can see the logs associated with the query execution.  If your query fails this is a good place to get additional information for troubleshooting.
    2. Results: You can view results in sets of 50 by default.
  6. There are six sliding views on the right hand side with the following capabilities, which are in context of the tab you are in:
    1. Query: This is the default operation,which allows you to write and edit SQL.
    2. Settings:  This allows you to set properties globally or associated with an individual query.
    3. Data Visualization: Allows you to visualize your numeric data through different charts.
    4. Visual Explain: This will generate an explain for the query.  This will also show the progress of the query.
    5. TEZ: If you use TEZ as the query execution engine then you can view the DAG associated with the query.  This integrates the TEZ User View so you can check for correctness and helps with performance tuning by visualizing the TEZ jobs associated with a SQL query.
    6. Notifications: This is how to get feedback on query execution.

The Apache Hive project provides a data warehouse view of the data in HDFS. Using a SQL dialect, HiveQL (HQL), Hive lets you create summarizations of your data and perform ad-hoc queries and analysis of large datasets in the Hadoop cluster. The overall approach with Hive is to project a table structure on the dataset and then manipulate it with SQL.   The notion of projecting a table structure on a file is often referred to as Schema-On-Read.   Since you are using data in HDFS, your operations can be scaled across all the datanodes and you can manipulate huge datasets.

4.4 Introduction: Apache Pig

MapReduce allows allows you to specify map and reduce functions, but working out how to fit your data processing into this pattern may sometimes require you to write multiple MapReduce stages. With Pig, data structures are much richer and the transformations you can apply to data are much more powerful.

4.4.1 Goals of this Module

  • Understanding Apache Pig
  • Understanding Apache Pig on Tez
  • Understanding Ambari Pig User Views on Hortonworks Sandbox

4.4.2 Apache Pig

Apache Pig allows Apache Hadoop users to write complex MapReduce transformations using a simple scripting language called Pig Latin. Pig translates the Pig Latin script into MapReduce so that it can be executed within YARN for access to a single dataset stored in the Hadoop Distributed File System (HDFS).

Pig was designed for performing a long series of data operations, making it ideal for three categories of Big Data jobs:

  • Extract-transform-load (ETL) data pipelines,
  • Research on raw data, and
  • Iterative data processing.

Whatever the use case, Pig will be:

Characteristic Benefit
Extensible Pig users can create custom functions to meet their particular processing requirements
Easily Programmed Complex tasks involving interrelated data transformations can be simplified and encoded as data flow sequences. Pig programs accomplish huge tasks, but they are easy to write and maintain.
Self-Optimizing Because the system automatically optimizes execution of Pig jobs, the user can focus on semantics.

Please refer the following video on Pig for more clarity:

4.4.3 How Pig Works

Pig runs on Apache Hadoop YARN and makes use of MapReduce and the Hadoop Distributed File System (HDFS). The language for the platform is called Pig Latin, which abstracts from the Java MapReduce idiom into a form similar to SQL. While SQL is designed to query the data, Pig Latin allows you to write a data flow that describes how your data will be transformed (such as aggregate, join and sort).

Since Pig Latin scripts can be graphs (instead of requiring a single output) it is possible to build complex data flows involving multiple inputs, transforms, and outputs. Users can extend Pig Latin by writing their own functions, using Java, Python, Ruby, or other scripting languages. Pig Latin is sometimes extended using UDFs (User Defined Functions), which the user can write in any of those languages and then call directly from the Pig Latin.

The user can run Pig in two modes, using either the “pig” command or the “java” command:

  • MapReduce Mode. This is the default mode, which requires access to a Hadoop cluster. The cluster may be a pseudo- or fully distributed one.
  • Local Mode. With access to a single machine, all files are installed and run using a local host and file system

4.4.4 Ambari Pig User Views on Hortonworks Sandbox

To get to the Ambari Pig User View on Sandbox, click on the User Views icon at top right and select Pig:

Screen Shot 2016-02-17 at 7.12.41 PM

This will bring up the Ambari Pig User View interface. Your Pig View does not have any scripts to display, so it will look like the following:

Pig_2

On the left is a list of your scripts, and on the right is a composition box for writing scripts. A special feature of the interface is the Pig helper at the bottom. The Pig helper will provide us with templates for the statements, functions, I/O statements, HCatLoader() and Python user defined functions. At the very bottom are status areas that will show the results of our script and log files.

The following screenshot shows and describes the various components and features of the Pig User View:

Pig_3

4.5 Suggested Readings

Hive Blogs:

Tez Blogs:
Apache Tez: A New Chapter in Hadoop Data Processing
Data Processing API in Apache TezORC Blogs:
Apache ORC Launches as a Top-Level Project
ORCFile in HDP 2: Better Compression, Better Performance

Lab 1 - Loading Sensor Data into HDFS

Introduction

In this section, you will download the sensor data and load that into HDFS using Ambari User Views. You will get introduced to the Ambari Files User View to manage files. You can perform tasks like create directories, navigate file systems and upload files to HDFS.  In addition, you’ll perform a few other file-related tasks as well.  Once you get the basics, you will create two directories and then load two files into HDFS using the Ambari Files User View.

Pre-Requisites

The tutorial is a part of series of hands on tutorial to get you started on HDP using Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial.

Outline

HDFS backdrop

A single physical machine gets saturated with its storage capacity as the data grows. This growth drives the need to partition your data across separate machines. This type of File system that manages storage of data across a network of machines is called Distributed File Systems. HDFS is a core component of Apache Hadoop and is designed to store large files with streaming data access patterns, running on clusters of commodity hardware. With Hortonworks Data Platform HDP 2.2, HDFS is now expanded to support heterogeneous storage  media within the HDFS cluster.

Step 1.1: Download and Extract the Sensor Data Files

1. You can download the sample sensor data contained in a compressed (.zip) folder here:  Geolocation.zip

2. Save the Geolocation.zip file to your computer, then extract the files. You should see a Geolocation folder that contains the following files:
* geolocation.csv – This is the collected geolocation data from the trucks. It contains records showing truck location, date, time, type of event, speed, etc.
* trucks.csv – This is data was exported from a relational database and it shows info on truck models, driverid, truckid, and aggregated mileage info.

Step 1.2: Load the Sensor Data into HDFS

1. Go to Ambari Dashboard and open the HDFS Files view. Click on the 9 square Ambari User Views icon next to the username button and select the HDFS Files menu item.

Screen Shot 2015-07-21 at 10.17.21 AM

2. Start from the top root of the HDFS file system, you will see all the files the logged in user (maria_dev in this case) has access to see:

Lab2_2

3. Navigate to /user/maria_dev directory by clicking on the directory links.

4. Let’s create a data directory to upload the data that we are going to use for this use case. Click the Lab2_3 button to create the data directory inside the maria_dev directory. Now navigate into the data directory.

add_new_folder_data_lab1

1.2.1 Upload Geolocation and Trucks CSV Files to data Folder

4. If you’re not already in your newly created directory path /user/maria_dev/data, go to the data folder. Then click on the upload_icon_lab1 button to upload the corresponding geolocation.csv and trucks.csv files into it.

5. An Upload file window will appear, click on the cloud symbol.

upload_file_lab1

6. Another window will appear, navigate to the destination the two csv files were downloaded. Click on one at a time, press open to complete the upload. Repeat the process until both files are uploaded.

upload_file_window_lab1

Both files are uploaded to HDFS as shown in the Files View UI:

uploaded_files_lab1

You can also perform the following operations on a file or folder by clicking on the entity’s row: Open, Rename, Permissions, Delete, Copy, Move, Download and concatenate.

1.2.2 Set Write Permissions to Write to data Folder

1. click on the data folder’s row, which is contained within the directory path /user/maria_dev. Click Permissions. Make sure that the background of all the write boxes are checked (blue). Refer to image for a visual explanation.

edit_permissions_lab1

Summary

Congratulations! Let’s summarize the skills and knowledge we acquired from this tutorial. We learned Hadoop Distributed File System (HDFS) was built to manage storing data across multiple machines. Now we can upload data into the HDFS using Ambari’s HDFS Files view.

Suggested Reading

Lab 2 - Hive and Data ETL

Introduction

In this tutorial, you will be introduced to Apache(TM) Hive. In the earlier section, we covered how to load data into HDFS. So now you have geolocation and trucks files stored in HDFS as csv files. In order to use this data in Hive, we will guide you on how to create a table and how to move data into a Hive warehouse, from where it can be queried. We will analyze this data using SQL queries in Hive User Views and store it as ORC. We will also walk through Apache Tez and how a DAG is created when you specify Tez as execution engine for Hive. Let’s start..!!

Pre-Requisites

The tutorial is a part of a series of hands on tutorials to get you started on HDP using the Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial.

Outline

Apache Hive

Apache Hive provides SQL interface to query data stored in various databases and files systems that integrate with Hadoop. Hive enables analysts familiar with SQL to run queries on large volumes of data. Hive has three main functions: data summarization, query and analysis. Hive provides tools that enable easy data extraction, transformation and loading (ETL).

Step 2.1: Become Familiar with Ambari Hive View

Apache Hive presents a relational view of data in HDFS. Hive can represent data in a tabular format managed by Hive or just stored in HDFS irrespective in the file format their data is stored in. Hive can query data from RCFile format, text files, ORC, JSON, parquet, sequence files and many of other formats in a tabular view. Through the use of SQL you can view your data as a table and create queries like you would in an RDBMS.

To make it easy to interact with Hive we use a tool in the Hortonworks Sandbox called the Ambari Hive View. Ambari Hive View provides an interactive interface to Hive. We can create, edit, save and run queries, and have Hive evaluate them for us using a series of MapReduce jobs or Tez jobs.

Let’s now open the Ambari Hive View and get introduced to the environment. Go to the 9 square Ambari User View icon and select Hive View:

Screen Shot 2015-07-21 at 10.10.18 AM

The Ambari Hive View looks like the following:

Lab2_2

Now let’s take a closer look at the SQL editing capabilities in the Hive View:

  1. There are five tabs to interact with SQL:
    1. Query: This is the interface shown above and the primary interface to write, edit and execute new SQL statements
    2. Saved Queries: You can save your favorite queries and quickly have access to them to rerun or edit.
    3. History: This allows you to look at past queries or currently running queries to view, edit and rerun.  It also allows you to see all SQL queries you have authority to view.  For example, if you are an operator and an analyst needs help with a query, then the Hadoop operator can use the History feature to see the query that was sent from the reporting tool.
    4. UDFs:  Allows you to define UDF interfaces and associated classes so you can access them from the SQL editor.
    5. Upload Table: Allows you to upload your hive query tables to your preferred database and appears instantly in the Query Editor for execution.
  2. Database Explorer:  The Database Explorer helps you navigate your database objects.  You can either search for a database object in the Search tables dialog box, or you can navigate through Database -> Table -> Columns in the navigation pane.
  3. Query Editor: The principal pane to write and edit SQL statements. This editor includes content assist via CTRL + Space to help you build queries. Content assist helps you with SQL syntax and table objects.
  4. Once you have created your SQL statement you have 4 options:
    1. Execute: This runs the SQL statement.
    2. Explain: This provides you a visual plan, from the Hive optimizer, of how the SQL statement will be executed.
    3. Save as:  Allows you to persist your queries into your list of saved queries.
    4. Kill Session: Terminates the SQL statement.
  5. When the query is executed you can see the Logs or the actual query results.
    1. Logs Tab: When the query is executed you can see the logs associated with the query execution.  If your query fails this is a good place to get additional information for troubleshooting.
    2. Results Tab: You can view results in sets of 50 by default.
  6. There are five sliding views on the right hand side with the following capabilities, which are in context of the tab you are in:
    1. Query: This is the default operation,which allows you to write and edit SQL.
    2. Settings:  This allows you to set properties globally or associated with an individual query.
    3. Data Visualization: Allows you to visualize your numeric data through different charts.
    4. Visual Explain: This will generate an explain for the query.  This will also show the progress of the query.
    5. TEZ: If you use TEZ as the query execution engine then you can view the DAG associated with the query.  This integrates the TEZ User View so you can check for correctness and helps with performance tuning by visualizing the TEZ jobs associated with a SQL query.
    6. Notifications: This is how to get feedback on query execution.

Take a few minutes to explore the various Hive View features.

2.1.1 Set hive.execution.engine as Tez

A feature we will configure before we run our hive queries is to set the hive execution engine as Tez. You can try map reduce if you like. We will use Tez in this tutorial.

1. Click on the gear in the sidebar referred to as number 6 in the interface above.

2. Click on the dropdown menu, choose hive.execution.engine and set the value as tez. Now we are ready to run our queries for this tutorial.

Step 2.2: Define a Hive Table

Now that you are familiar with the Hive View, let’s create and load tables for the geolocation and trucks data. In this section we will learn how to use the Ambari Hive View to create two tables: geolocation and trucking using the Hive View Upload Table tab. The Upload Table tab provides the following key options: choose input file type, storage options (i.e. Apache ORC) and set first row as header. Here is a visual representation of the table and load creation process accomplish in the next few steps.:

create_tables_architecture

2.2.1 Create and load Trucks table For Staging Initial Load

Navigate and select the Upload Table of the Ambari Hive View. Then select the Upload from HDFS radio button, enter the HDFS path /user/maria_dev/data/trucks.csv and click the Preview button:

upload_table_hdfs_path

You should see a similar dialog:
Note that the first row contains the names of the columns.

click_gear_button

Fortunately the Upload Table tab has a feature to specify the first row as a header for the column names. Press the Gear Button next to the File type pull down menu, shown above, to file type customization window. Then check the checkbox for the Is first row header? and hit the close button.

first_row_header

You should now see a similar dialog box with the names of the header columns as the names of the columns:

upload_table

Once you have finished setting all the various properties select the Upload Table button to start the create and load table process.

upload_progress

Before reviewing what is happening behind the covers in the Upload Progress let’s learn learn more about Hive File Formats.

2.2.2: Define an ORC Table in Hive Create table using Apache ORC file format

Introducing Apache ORC is a fast columnar storage file format for Hadoop workloads.

The Optimized Row Columnar (new Apache ORC project) file format provides a highly efficient way to store Hive data. It was designed to overcome limitations of the other Hive file formats. Using ORC files improves performance when Hive is reading, writing, and processing data.

To use the ORC format, specify ORC as the file format when creating the table. Here is an example::

CREATE TABLE … **STORED AS ORC**
CREATE TABLE trucks STORED AS ORC AS SELECT * FROM trucks_temp_table;

Similar style create statements are used with the temporary tables used in the Upload Tables tab.

2.2.3: Review Upload Table Progress Steps

Initially the trucks.csv table is created and loaded into a temporary table. The temporary table is used to create and load data in ORC format using syntax explained in previous step. Once the data is loaded into final table the temporary tables are deleted.

create_tables_architecture

NOTE: The temporary table names are random set of characters and not the names in the illustration above.

You can review the SQL statements issued by selecting the History tab and clicking on the 4 Internal Job that were executed as a result of using the Upload Table tab.

job_history

2.2.4 Create and Load Geolocation Table

Repeat the steps above with the geolocation.csv file to create and load the geolocation table using the ORC file format.

2.2.5 Hive Create Table Statement

Let’s review some aspects of the CREATE TABLE statements generated and issued above.  If you have an SQL background this statement should seem very familiar except for the last 3 lines after the columns definition:

  • The ROW FORMAT clause specifies each row is terminated by the new line character.
  • The FIELDS TERMINATED BY clause specifies that the fields associated with the table (in our case, the two csv files) are to be delimited by a comma.
  • The STORED AS clause specifies that the table will be stored in the TEXTFILE format.

NOTE: For details on these clauses consult the Apache Hive Language Manual.

2.2.6 Verify New Tables Exist

To verify the tables were defined successfully, click the refresh icon in the Database Explorer. Under Databases, click default database to expand the list of table and the new tables should appear:

select_data_trucks

2.2.7 Sample Data from the trucks table

Click on the Load sample data icon to generate and execute a select SQL statement to query the table for a 100 rows.

  • You can have multiple SQL statements within each editor worksheet, but each statement needs to be separated by a semicolon “;”.
  • If you have multiple statements within a worksheet but you only want to run one of them just highlight the statement you want to run and then click the Execute button.

A few additional commands to explore tables:

  • show tables; – List the tables created in the database by looking up the list of tables from the metadata stored in HCatalogdescribe
  • {table_name}; – Provides a list of columns for a particular table (ie describe geolocation_stage;)
  • show create {table_name}; – Provides the DDL to recreate a table (ie show create table geolocation_stage;)
  • describe formatted {table_name}; – Explore additional metadata about the table. For example you can verify geolocation is an ORC Table, execute the following query:
describe formatted geolocation;

Scroll down to the bottom of the Results tab and you will see a section labeled Storage Information. The output should look like:

storage_information

By default, when you create a table in Hive, a directory with the same name gets created in the /apps/hive/warehouse folder in HDFS. Using the Ambari Files View, navigate to the /apps/hive/warehouse folder. You should see both a geolocation and trucks directory:

NOTE: The definition of a Hive table and its associated metadata (i.e., the directory the data is stored in, the file format, what Hive properties are set, etc.) are stored in the Hive metastore, which on the Sandbox is a MySQL database.

2.2.8 Rename Query Editor Worksheet

Notice the tab of your new Worksheet is labeled trucks sample data. Double-click on the worksheet tab to rename the label to “sample truck data”. Now save this worksheet by clicking the button.

save_truck_sample_data

2.2.9 Command Line Approach: Populate Hive Table with Data

The following Hive command can be used to LOAD data into existing table from the command line

LOAD DATA INPATH '/user/maria_dev/data/trucks.csv' OVERWRITE INTO TABLE trucks;

If you would run the above commands and navigate to the /user/maria_dev/data folder. You would of notice the folder is empty! The LOAD DATA INPATH command moved the trucks.csv file from the /user/maria_dev/data folder to the /apps/hive/warehouse/trucks_stage folder.

2.2.10 Beeline – Command Shell

If you want to try running some of these commands from the the command line you can use the Beeline Shell. Beeline uses a JDBC connection to connect to HiveServer2. Follow the following steps from your shell in the box (or putty if using Windows):

i. Local Sandbox VM
Open up shell in the box to ssh into HDP with

~~~
ssh maria_dev@127.0.0.1 -p 2222 maria_dev
~~~

ii. su hive

iii. beeline Starts Beeline shell and now you can enter commands and SQL

iv. quit; Exits out of the Beeline shell.

What did you notice about performance after running hive queries from shell?

  • Queries using the shell run faster because hive runs the query directory in hadoop whereas in Ambari Hive View, the query must be accepted by a rest server before it can submitted to hadoop.
  • You can get more information on the Beeline from the Hive Wiki.
  • Beeline is based on SQLLine.

Step 2.3: Explore Hive Settings on Ambari Dashboard

2.3.1 Open Ambari Dashboard in New Tab

Click on the Dashboard tab to start exploring the Ambari Dashboard.

ambari_dashboard

2.3.2 Become Familiar with Hive Settings

Go to the Hive page then select the Configs tab then click on Settings tab:

ambari_dashboard_explanation

Once you click on the Hive page you should see a page similar to above:

  1. Hive Page
  2. Hive Configs Tab
  3. Hive Settings Tab
  4. Version History of Configuration

Scroll down to the Optimization Settings:

hive_optimization

In the above screenshot we can see:

  1. Tez is set as the optimization engine
  2. Cost Based Optimizer (CBO) is turned on

This shows the HDP 2.5 Ambari Smart Configurations, which simplifies setting configurations

  • Hadoop is configured by a collection of XML files.
  • In early versions of Hadoop, operators would need to do XML editing to change settings.  There was no default versioning.
  • Early Ambari interfaces made it easier to change values by showing the settings page with dialog boxes for the various settings and allowing you to edit them.  However, you needed to know what needed to go into the field and understand the range of values.
  • Now with Smart Configurations you can toggle binary features and use the slider bars with settings that have ranges.

By default the key configurations are displayed on the first page.  If the setting you are looking for is not on this page you can find additional settings in the Advanced tab:

hive_vectorization

For example, if we wanted to improve SQL performance, we can use the new Hive vectorization features. These settings can be found and enabled by following these steps:

  1. Click on the Advanced tab and scroll to find the property
  2. Or, start typing in the property into the property search field and then this would filter the setting you scroll for.

As you can see from the green circle above, the Enable Vectorization and Map Vectorization is turned on already.

Some key resources to learn more about vectorization and some of the key settings in Hive tuning:

Step 2.4: Analyze the Trucks Data

Next we will be using Hive, Pig and Zeppelin to analyze derived data from the geolocation and trucks tables.  The business objective is to better understand the risk the company is under from fatigue of drivers, over-used trucks, and the impact of various trucking events on risk.   In order to accomplish this, we will apply a series of transformations to the source data, mostly though SQL, and use Pig or Spark to calculate risk.   In the last lab on Data Visualization, we will be using Zeppelin to generate a series of charts to better understand risk.

Lab2_21

Let’s get started with the first transformation.   We want to calculate the miles per gallon for each truck. We will start with our truck data table.  We need to sum up all the miles and gas columns on a per truck basis. Hive has a series of functions that can be used to reformat a table. The keyword LATERAL VIEW is how we invoke things. The stack function allows us to restructure the data into 3 columns labeled rdate, gas and mile (ex: ‘june13’, june13_miles, june13_gas) that make up a maximum of 54 rows. We pick truckid, driverid, rdate, miles, gas from our original table and add a calculated column for mpg (miles/gas).  And then we will calculate average mileage.

2.4.1 Create Table truck_mileage From Existing Trucking Data

Using the Ambari Hive User View, execute the following query:

CREATE TABLE truck_mileage STORED AS ORC AS SELECT truckid, driverid, rdate, miles, gas, miles / gas mpg FROM trucks LATERAL VIEW stack(54, 'jun13',jun13_miles,jun13_gas,'may13',may13_miles,may13_gas,'apr13',apr13_miles,apr13_gas,'mar13',mar13_miles,mar13_gas,'feb13',feb13_miles,feb13_gas,'jan13',jan13_miles,jan13_gas,'dec12',dec12_miles,dec12_gas,'nov12',nov12_miles,nov12_gas,'oct12',oct12_miles,oct12_gas,'sep12',sep12_miles,sep12_gas,'aug12',aug12_miles,aug12_gas,'jul12',jul12_miles,jul12_gas,'jun12',jun12_miles,jun12_gas,'may12',may12_miles,may12_gas,'apr12',apr12_miles,apr12_gas,'mar12',mar12_miles,mar12_gas,'feb12',feb12_miles,feb12_gas,'jan12',jan12_miles,jan12_gas,'dec11',dec11_miles,dec11_gas,'nov11',nov11_miles,nov11_gas,'oct11',oct11_miles,oct11_gas,'sep11',sep11_miles,sep11_gas,'aug11',aug11_miles,aug11_gas,'jul11',jul11_miles,jul11_gas,'jun11',jun11_miles,jun11_gas,'may11',may11_miles,may11_gas,'apr11',apr11_miles,apr11_gas,'mar11',mar11_miles,mar11_gas,'feb11',feb11_miles,feb11_gas,'jan11',jan11_miles,jan11_gas,'dec10',dec10_miles,dec10_gas,'nov10',nov10_miles,nov10_gas,'oct10',oct10_miles,oct10_gas,'sep10',sep10_miles,sep10_gas,'aug10',aug10_miles,aug10_gas,'jul10',jul10_miles,jul10_gas,'jun10',jun10_miles,jun10_gas,'may10',may10_miles,may10_gas,'apr10',apr10_miles,apr10_gas,'mar10',mar10_miles,mar10_gas,'feb10',feb10_miles,feb10_gas,'jan10',jan10_miles,jan10_gas,'dec09',dec09_miles,dec09_gas,'nov09',nov09_miles,nov09_gas,'oct09',oct09_miles,oct09_gas,'sep09',sep09_miles,sep09_gas,'aug09',aug09_miles,aug09_gas,'jul09',jul09_miles,jul09_gas,'jun09',jun09_miles,jun09_gas,'may09',may09_miles,may09_gas,'apr09',apr09_miles,apr09_gas,'mar09',mar09_miles,mar09_gas,'feb09',feb09_miles,feb09_gas,'jan09',jan09_miles,jan09_gas ) dummyalias AS rdate, miles, gas;

create_table_truckmileage

2.4.2 Explore a sampling of the data in the truck_mileage table

To view the data generated by the script, click Load Sample Data icon in the Database Explorer next to truck_mileage. After clicking the next button once, you should see a table that lists each trip made by a truck and driver:

select_data_truck_mileage_lab2

2.4.3 Use the Content Assist to build a query

1.  Create a new SQL Worksheet.

2.  Start typing in the SELECT SQL command, but only enter the first two letters:

SE

3.  Press Ctrl+space to view the following content assist pop-up dialog window:

Lab2_24

NOTE: Notice content assist shows you some options that start with an “SE”. These shortcuts will be great for when you write a lot of custom query code.

4. Type in the following query, using Ctrl+space throughout your typing so that you can get an idea of what content assist can do and how it works:

SELECT truckid, avg(mpg) avgmpg FROM truck_mileage GROUP BY truckid;

Lab2_28

5.  Click the “Save as …” button to save the query as “average mpg“:

Lab2_26

6.  Notice your query now shows up in the list of “Saved Queries“, which is one of the tabs at the top of the Hive User View.

7.  Execute the “average mpg” query and view its results.

2.4.4 Explore Explain Features of the Hive Query Editor

1. Now let’s explore the various explain features to better understand the execution of a query: Text Explain, Visual Explain and Tez Explain. Click on the Explain button:

Lab2_27

2. You shall receive similar image as below. The following output displays the flow of the resulting Tez job:

tez_job_result

3. To see the Visual Explain, click on the Visual Explain icon on the right tabs. This is a much more readable summary of the explain plan:

visual_explain_dag

2.4.5 Explore TEZ

1. If you click on TEZ View from Ambari Views at the top, you can see DAG details associated with the previous hive and pig jobs.

tez_view

2. Select the first DAG as it represents the last job that was executed.

all_dags

3. There are seven tabs at the top left please take a few minutes to explore the various tabs and then click on the Graphical View tab and hover over one of the nodes with your cursor to get more details on the processing in that node.

Lab2_35

4. Let’s also view Vertex Swimlane. This feature helps with troubleshooting of TEZ jobs. As you will see in the image there is a graph for Map 1 and Reduce 2. These graphs are timelines for when events happened. Hover over red or blue line to view a event tooltip.

Basic Terminology:

  • Bubble represents an event
  • Vertex represents the solid line, timeline of events

For map1, the tooltip shows that the events vertex started and vertex initialize occur simultaneously:

tez_vertex_swimlane_map1_lab2

For Reducer 2, the tooltip shows that the events vertex started and initialize share 1 second difference on execution time.

Vertex Initialize

tez_vertex_swimlane_reducer2_initial_lab2

Vertex started

tez_vertex_swimlane_reducer2_started_lab2

When you look at the tasks started for and finished (thick line) for Map1 compared to Reducer2 in the graph, what do you notice?

  • Map1 starts and completes before Reducer2.

5. Go back to the Hive View and save the query by clicking the Save as … button.

2.4.6 Create Table truck avg_mileage From Existing trucks_mileage Data

Note: Verify that the hive.execution.engine is under tez.

Persist these results into a table, this is a fairly common pattern in Hive and it is called Create Table As Select (CTAS ).  Paste the following script into a new Worksheet, then click the Execute button:

CREATE TABLE avg_mileage
STORED AS ORC
AS
SELECT truckid, avg(mpg) avgmpg
FROM truck_mileage
GROUP BY truckid;

average_mile_table_query

2.4.7 Load Sample Data of avg_mileage

To view the data generated by the script, click Load sample data icon in the Database Explorer next to avg_mileage. You see our table is now a list of each trip made by a truck.

results_avg_mileage_table

Step 2.5: Define Table Schema

Now we have refined the truck data to get the average mpg for each truck (avg_mileage table). The next task is to compute the risk factor for each driver which is the total miles driven/abnormal events. We can get the event information from the geolocation table.

Lab3_1

If we look at the truck_mileage table, we have the driverid and the number of miles for each trip. To get the total miles for each driver, we can group those records by driverid and then sum the miles.

2.5.1 Create Table DriverMileage from Existing truck_mileage Data

We will start by creating a table named driver_mileage that is created from a query of the columns we want from truck_mileage. The following query groups the records by driverid and sums the miles in the select statement. Execute the query below in a new Worksheet:

CREATE TABLE DriverMileage
STORED AS ORC
AS
SELECT driverid, sum(miles) totmiles
FROM truck_mileage
GROUP BY driverid;

create_table_driver_mileage

Note: This table is essential for both Pig Latin and Spark jobs.

2.5.2 View Data Generated by Query

To view data, click the Load sample data icon in the Database Explorer next to drivermileage. The results should look like:

select_data_drivermileage

2.5.3 Explore Hive Data Visualization

This tool enables us to transform our hive data into a visualization that makes data easier to understand. Let’s explore the Hive data explorer to see a variety of different data visualizations. We’ll use these examples to build a custom
visualization, which will show the user

1. Issue a query by (1)clicking on the geolocation Load sample data icon and then (2) select the Hive View visualization tab

select_data_geolocation

2. Click on Data Explorer tab and quickly explore the distribution of the data from the query.

hive_explorer

3. You can also explore some custom Data Visualizations by click the tab and then dragging 2 columns into the Positional fields. Note that you can not save these graphs. Explore the following HCC article for more info.

hive_visualization

Summary

Congratulations! Let’s summarize some Hive commands we learned to process, filter and manipulate the geolocation and trucks data.
We now can create Hive tables with CREATE TABLE and load data into them using the LOAD DATA INPATH command. Additionally, we learned how to change the file format of the tables to ORC, so hive is more efficient at reading, writing and processing this data. We learned to grab parameters from our existing table using SELECT {column_name…} FROM {table_name} to create a new filtered table.

Suggested Readings

Augment your hive foundation with the following resources:

Lab 3 - Pig Risk Factor Analysis

Introduction

In this tutorial, you will be introduced to Apache Pig. In the earlier section of lab, you learned how to load data into HDFS and then manipulate it using Hive. We are using the Truck sensor data to better understand risk associated with every driver. This section will teach you to compute risk using Apache Pig.

Pre-Requisites

The tutorial is a part of series of hands on tutorial to get you started on HDP using Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial.

Outline

Pig Basics

Pig is a high-level scripting language used with Apache Hadoop. Pig enables data workers to write complex data transformations without knowing Java. Pig’s simple SQL-like scripting language is called Pig Latin, and appeals to developers already familiar with scripting languages and SQL.

Pig is complete, so you can do all required data manipulations in Apache Hadoop with Pig. Through the User Defined Functions(UDF) facility in Pig, Pig can invoke code in many languages like JRuby, Jython and Java. You can also embed Pig scripts in other languages. The result is that you can use Pig as a component to build larger and more complex applications that tackle real business problems.

Pig works with data from many sources, including structured and unstructured data, and store the results into the Hadoop Data File System.

Pig scripts are translated into a series of MapReduce jobs that are run on the Apache Hadoop cluster.

Create Table riskfactor from Existing trucks_mileage Data

Next, you will use Pig to compute the risk factor of each driver. Before we can run the Pig code, the table must already exist in Hive to satisfy one of the requirements for the HCatStorer() class. The Pig code expects the following structure for a table named riskfactor. Execute the following DDL command:

CREATE TABLE riskfactor (driverid string,events bigint,totmiles double,riskfactor float)
STORED AS ORC;

riskfactor_table

Verify Table riskfactor was Created Successfully

Verify the riskfactor table was created successfully. It will be empty now, but you will populate it from a Pig script. You are now ready to compute the risk factor using Pig. Let’s take a look at Pig and how to execute Pig scripts from within Ambari.

Step 3.1: Create Pig Script

In this phase of the tutorial, we create and run a Pig script. We will use the Ambari Pig View. Let’s get started…

3.1.1 Log in to Ambari Pig User Views

To get to the Ambari Pig View, click on the Ambari Views icon at top right and select Pig:

Screen Shot 2015-07-21 at 10.12.41 AM

This will bring up the Ambari Pig User View interface. Your Pig View does not have any scripts to display, so it will look like the following:

Lab3_4

On the left is a list of your scripts, and on the right is a composition box for writing scripts. A special interface feature is the Pig helper located below the name of your script file. The Pig helper provides us with templates for the statements, functions, I/O statements, HCatLoader() and Python user defined functions. At the very bottom are status areas that will show the results of our script and log files.

The following screenshot shows and describes the various components and features of the Pig View:

Lab3_5

3.1.2 Create a New Script

Let’s enter a Pig script. Click the New Script button in the upper-right corner of the view:

Lab3_6

Name the script riskfactor.pig, then click the Create button:

Lab3_7

3.1.3 Load Data in Pig using Hcatalog

We will use HCatalog to load data into Pig. HCatalog allows us to share schema across tools and users within our Hadoop environment. It also allows us to factor out schema and location information from our queries and scripts and centralize them in a common repository. Since it is in HCatalog we can use the HCatLoader() function. Pig allows us to give the table a name or alias and not have to worry about allocating space and defining the structure. We just have to worry about how we are processing the table.

  • We can use the Pig helper located below the name of your script file to give us a template for the line. Click on Pig helper -> HCatalog->load template
  • The entry %TABLE% is highlighted in red for us. Type the name of the table which is geolocation.
  • Remember to add the a = before the template. This saves the results into a. Note the ‘=’ has to have a space before and after it.
  • Our completed line of code will look like:
a = LOAD 'geolocation' using org.apache.hive.hcatalog.pig.HCatLoader();

The script above loads data, in our case, from a file named geolocation using the HCatLoader() function. Copy-and-paste the above Pig code into the riskfactor.pig window.

Note: Refer to Pig Latin Basics – load to learn more about the load operator.

3.1.4 Filter your data set

The next step is to select a subset of the records, so we have the records of drivers for which the event is not normal. To do this in Pig we use the Filter operator. We instruct Pig to Filter our table and keep all records where event !=”normal” and store this in b. With this one simple statement, Pig will look at each record in the table and filter out all the ones that do not meet our criteria.

  • We can use Pig Help again by clicking on Pig helper->Relational Operators->FILTER template
  • We can replace %VAR% with “a” (hint: tab jumps you to the next field)
  • Our %COND% is “event !=’normal’; ” (note: single quotes are needed around normal and don’t forget the trailing semi-colon)
  • Complete line of code will look like:
b = filter a by event != 'normal';

Copy-and-paste the above Pig code into the riskfactor.pig window.

Note: Refer to Pig Latin Basics – filter to learn more about the filter operator.

3.1.5 Iterate your data set

Since we have the right set of records, let’s iterate through them. We use the “foreach” operator on the grouped data to iterate through all the records. We would also like to know the number of non normal events associated with a driver, so to achieve this we add ‘1’ to every row in the data set.

  • Pig helper ->Relational Operators->FOREACH template will get us the code
  • Our %DATA% is b and the second %NEW_DATA% is “driverid,event,(int) ‘1’ as occurance;
  • Complete line of code will look like:
c = foreach b generate driverid, event, (int) '1' as occurance;

Copy-and-paste the above Pig code into the riskfactor.pig window:

Note: Refer to Pig Latin Basics – foreach to learn more about the foreach operator.

3.1.6 Calculate the total non normal events for each driver

The group statement is important because it groups the records by one or more relations. In our case, we want to group by driver id and iterate over each row again to sum the non normal events.

  • Pig helper ->Relational Operators->GROUP %VAR% BY %VAR% template will get us the code
  • First %VAR% takes “c” and second %VAR% takes “driverid;
  • Complete line of code will look like:
d = group c by driverid;

Copy-and-paste the above Pig code into the riskfactor.pig window.

  • Next use Foreach statement again to add the occurance.
e = foreach d generate group as driverid, SUM(c.occurance) as t_occ;

Note: Refer to Pig Latin Basics – group to learn more about the group operator.

3.1.7 Load drivermileage Table and Perform a Join Operation

In this section, we will load drivermileage table into Pig using Hcatlog and perform a join operation on driverid. The resulting data set will give us total miles and total non normal events for a particular driver.

  • Load drivermileage using HcatLoader()
g = LOAD 'drivermileage' using org.apache.hive.hcatalog.pig.HCatLoader();
  • Pig helper ->Relational Operators->JOIN %VAR% BY template will get us the code
  • Replace %VAR% by ‘e‘ and after BY put ‘driverid, g by driverid;
  • Complete line of code will look like:
h = join e by driverid, g by driverid;

Copy-and-paste the above two Pig codes into the riskfactor.pig window.

Note: Refer to Pig Latin Basics – join to learn more about the join operator.

3.1.8 Compute Driver Risk factor

In this section, we will associate a driver risk factor with every driver. To calculate driver risk factor, divide total miles travelled by non normal event occurrences.

  • We will use Foreach statement again to compute driver risk factor for each driver.
  • Use the following code and paste it into your Pig script.
final_data = foreach h generate $0 as driverid, $1 as events, $3 as totmiles, (float) $3/$1 as riskfactor;
  • As a final step, store the data into a table using Hcatalog.
store final_data into 'riskfactor' using org.apache.hive.hcatalog.pig.HCatStorer();

Here is the final code and what it will look like once you paste it into the editor.

Note: Refer to Pig Latin Basics – store to learn more about the store operator.

Geolocation has data stored in ORC format

a = LOAD 'geolocation' using org.apache.hive.hcatalog.pig.HCatLoader();
b = filter a by event != 'normal';
c = foreach b generate driverid, event, (int) '1' as occurance;
d = group c by driverid;
e = foreach d generate group as driverid, SUM(c.occurance) as t_occ;
g = LOAD 'drivermileage' using org.apache.hive.hcatalog.pig.HCatLoader();
h = join e by driverid, g by driverid;
final_data = foreach h generate $0 as driverid, $1 as events, $3 as totmiles, (float) $3/$1 as riskfactor;
store final_data into 'riskfactor' using org.apache.hive.hcatalog.pig.HCatStorer();

Lab3_8

Save the file riskfactor.pig by clicking the Save button in the left-hand column.

Step 3.2: Quick Recap

Before we execute the code, let’s review the code again:

  • The line a= loads the geolocation table from HCatalog.
  • The line b= filters out all the rows where the event is not ‘Normal’.
  • Then we add a column called occurrence and assign it a value of 1.
  • We then group the records by driverid and sum up the occurrences for each driver.
  • At this point we need the miles driven by each driver, so we load the table we created using Hive.
  • To get our final result, we join by the driverid the count of events in e with the mileage data in g.
  • Now it is real simple to calculate the risk factor by dividing the miles driven by the number of events

You need to configure the Pig Editor to use HCatalog so that the Pig script can load the proper libraries. In the Pig arguments text box, enter -useHCatalog and click the Add button:

Note this argument is case sensitive. It should be typed exactly “-useHCatalog”.

Lab3_9

The Arguments section of the Pig View should now look like the following:
Lab3_10

Step 3.3: Execute Pig Script on Tez

3.3.1 Execute Pig Script

Click Execute on Tez checkbox and finally hit the blue Execute button to submit the job. Pig job will be submitted to the cluster. This will generate a new tab with a status of the running of the Pig job and at the top you will find a progress bar that shows the job status.

Lab3_11

3.3.2 View Results Section

Wait for the job to complete. The output of the job is displayed in the Results section. Notice your script does not output any result – it stores the result into a Hive table – so your Results section will be empty.

Lab3_12

Lab3_13

Click on the Logs dropdown menu to see what happened when your script ran. Errors will appear here.

3.3.3 View Logs section (Debugging Practice)

Why are Logs important?

The logs section is helpful when debugging code after expected output does not happen. For instance, say in the next section, we load the sample data from our riskfactor table and nothing appears. Logs will tell us why the job failed. A common issue that could happen is that pig does not successfully read data from the geolocation table or drivermileage table. Therefore, we can effectively address the issue.

Let’s verify pig read from these tables successfully and stored the data into our riskfactor table. You should receive similar output:

debug_through_logs_lab3

What results do our logs show us about our Pig Script?

  • Read 8000 records from our geolocation table
  • Read 100 records from our drivermileage table
  • Stored 99 records into our riskfactor table

Can you think of scenarios in which these results if different would help us debug our script?
For example, say 0 records were read from the geolocation table, how would you solve the problem?

3.3.4 Verify Pig Script Successfully Populated Hive Table

Go back to the Ambari Hive User View and browse the data in the riskfactor table to verify that your Pig job successfully populated this table. Here is what is should look like:

Lab3_14

At this point we now have our truck miles per gallon table and our risk factor table. The next step is to pull this data into Excel to create the charts for the visualization step.

Summary

Congratulations! Let’s summarize the Pig commands we learned in this tutorial to compute risk factor analysis on the geolocation and truck data. We learned to use Pig to access the data from Hive using the LOAD {hive_table} …HCatLoader() script. Therefore, we were able to perform the filter, foreach, group, join, and store {hive_table} …HCatStorer() scripts to manipulate, transform and process this data. To review these bold pig latin operators, view the Pig Latin Basics, which contains documentation on each operator.

Suggested Readings

Strengthen your foundation of pig latin and reinforce why this scripting platform is benficial for processing and analyzing massive data sets with these resources:

Lab 4 - Spark Risk Factor Analysis

Note: This lab is optional and produces the same result as in Lab 3. You may continue on to the next lab if you wish.

Introduction

In this tutorial we will introduce Apache Spark. In the earlier section of the lab you have learned how to load data into HDFS and then manipulate it using Hive. We are using the Truck sensor data to better understand risk associated with every driver. This section will teach you how to compute risk using Apache spark.

Pre-Requisites

This tutorial is a part of a series of hands on tutorials to get you started on HDP using the Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial.

Outline

Background

MapReduce has been useful, but the amount of time it takes for the jobs to run can at times be exhaustive. Also, MapReduce jobs only work for a specific set of use cases. There is a need for computing framework that works for a wider set of use cases.

Apache Spark was designed to be a fast, general-purpose, easy-to-use computing platform. It extends the MapReduce model and takes it to a whole other level. The speed comes from the in-memory computations. Applications running in memory allow for much faster processing and response.

Apache Spark

Apache Spark is a fast, in-memory data processing engine with elegant and expressive development APIs in Scala,Java, and Python and R that allow data workers to efficiently execute machine learning algorithms that require fast iterative access to datasets. Spark on Apache Hadoop YARN enables deep integration with Hadoop and other YARN enabled workloads in the enterprise.

You can run batch application such as MapReduce types jobs or iterative algorithms that build upon each other. You can also run interactive queries and process streaming data with your application. Spark also provides a number of libraries which you can easily use to expand beyond the basic Spark capabilities such as Machine Learning algorithms, SQL, streaming, and graph processing. Spark runs on Hadoop clusters such as Hadoop YARN or Apache Mesos, or even in a Standalone Mode with its own scheduler. The Sandbox includes both Spark 1.6 and Spark 2.0.

Lab4_1

Let’s get started!

Step 4.1: Configure Spark services using Ambari

1. Log on to Ambari Dashboard as maria_dev. At the bottom left corner of the services column, check that Spark and Zeppelin are running.

Note: If these services are disabled, start these services.

ambari_dashboard_lab4

For HDP 2.5 Sandbox Users Activate Livy Server

Livy Server is a new feature added to the latest Sandbox HDP Platform and it adds extra security while running our spark jobs from Zeppelin Notebook. For this lab, users that have HDP 2.5 Sandbox can use Livy.

2. Now verify the Spark livy server is running:

verify_spark_livy_server_lab4

3. As you can see our server is down. We need to start it before running spark jobs in Zeppelin. Click on Livy Server, then click on sandbox.hortonworks.com. Now we let’s scroll down to livy server, press on the Stopped button and start the server. Press the OK button in the Confirmation window.

start_livy_server_lab4

Livy Server Started:

livy_server_running_lab4

4. Go back into the Spark Service. Click on Service Actions -> Turn Off Maintenance Mode.

Log out of Ambari.

4.1.1 There are two ways to access Zeppelin.

1. The first way, open Zeppelin View from Ambari views selector:

zeppelin_view_lab4

2. Below is an image of the welcome screen from Zeppelin View, as you can see users must login to create notebooks:

zeppelin_view_welcome_lab4

3. The second way is to access Zeppelin at sandbox.hortonworks.com:9995 through its port number:

<hostname>:9995

Refer to Learning the Ropes of Hortonworks Sandbox if you need assistance figuring out your hostname.

You should see a Zeppelin Welcome Page:

zeppelin_welcome_page

Optionally, if you want to find out how to access the Spark shell to run code on Spark refer to Appendix A.

5. Create a Zeppelin Notebook

Click on a Notebook tab at the top left and hit Create new note. Name your notebook Compute Riskfactor with Spark. By the default, the notebook will load Spark Scala API.

create_new_notebook

notebook_name

Step 4.2: Create a HiveContext

For improved Hive integration, HDP 2.5 offers ORC file support for Spark. This allows Spark to read data stored in ORC files. Spark can leverage ORC file’s more efficient columnar storage and predicate pushdown capability for even faster in-memory processing. HiveContext is an instance of the Spark SQL execution engine that integrates with data stored in Hive. The more basic SQLContext provides a subset of the Spark SQL support that does not depend on Hive. It reads the configuration for Hive from hive-site.xml on the classpath.

Import sql libraries:

If you have gone through Pig section, you have to drop the table riskfactor so that you can populate it again using Spark. Copy and paste the following code into your Zeppelin notebook, then click the play button. Alternatively, press shift+enter to run the code.

%hive
show tables

We will see that there is a table called riskfactor, let us drop that:

%hive
drop table riskfactor

To verify, let us do show tables again:

%hive
show tables

drop_table_lab4

Now create it back with the same DDL that we executed in the Pig section, Write the following query:

%hive
CREATE TABLE riskfactor (driverid string,events bigint,totmiles bigint,riskfactor float)
STORED AS ORC

create_table_riskfactor_lab4

We can either run the original %spark interpreter or the %livy spark interpreter to run spark code. The difference is that livy comes with more security. The default interpreter for spark jobs is %spark.

%spark
import org.apache.spark.sql.hive.orc._
import org.apache.spark.sql._

import_sql_libraries

Instantiate HiveContext

%spark
val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)

Lab4_6

  • sc stands for Spark Context. SparkContext is the main entry point to everything Spark. It can be used to create RDDs and shared variables on the cluster. When you start up the Spark Shell, the SparkContext is automatically initialized for you with the variable sc.

Step 4.3: Create a RDD from HiveContext

What is a RDD?

Spark’s primary core abstraction is called a Resilient Distributed Dataset or RDD. It is a distributed collection of elements that is parallelized across the cluster. In other words, a RDD is an immutable collection of objects that is partitioned and distributed across multiple physical nodes of a YARN cluster and that can be operated in parallel.

There are three methods for creating a RDD:

  1. Parallelize an existing collection. This means that the data already resides within Spark and can now be operated on in parallel.
    • Create a RDD by referencing a dataset. This dataset can come from any storage source supported by Hadoop such as HDFS, Cassandra, HBase etc.
    • Create a RDD by transforming an existing RDD to create a new RDD.

We will be using the later two methods in our tutorial.

RDD Transformations and Actions

Typically, RDDs are instantiated by loading data from a shared filesystem, HDFS, HBase, or any data source offering a Hadoop InputFormat on a YARN cluster.

Once a RDD is instantiated, you can apply a series of operations. All operations fall into one of two types: transformations or actions.

  • Transformation operations, as the name suggests, create new datasets from an existing RDD and build out the processing DAG that can then be applied on the partitioned dataset across the YARN cluster. Transformations do not return a value. In fact, nothing is evaluated during the definition of these transformation statements. Spark just creates these Direct Acyclic Graphs or DAG, which will only be evaluated at runtime. We call this lazy evaluation.
  • An Action operation, on the other hand, executes a DAG and returns a value.

4.3.1 View List of Tables in Hive Warehouse

Use a simple show command to see the list of tables in Hive warehouse.

%spark
hiveContext.sql("show tables").collect.foreach(println)

Lab4_7

Note: false indicates whether the column requires data.

You will notice that the geolocation table and the driver mileage table that we created earlier in an tutorial are already listed in Hive metastore and can be directly queried upon.

4.3.2 Query Tables To Build Spark RDD

We will do a simple select query to fetch data from geolocation and drivermileage tables to a spark variable. Getting data into Spark this way also allows to copy table schema to RDD.

%spark
val geolocation_temp1 = hiveContext.sql("select * from geolocation")

Lab4_8

%spark
val drivermileage_temp1 = hiveContext.sql("select * from drivermileage")

Lab4_9

4.4 Querying Against a Table

4.4.1 Registering a Temporary Table

Now let’s register a temporary table and use SQL syntax to query against that table.

%spark
geolocation_temp1.registerTempTable("geolocation_temp1")
drivermileage_temp1.registerTempTable("drivermileage_temp1")

name_rdd

Next, we will perform an iteration and a filter operation. First, we need to filter drivers that have non-normal events associated with them and then count the number for non-normal events for each driver.

%spark
val geolocation_temp2 = hiveContext.sql("SELECT driverid, count(driverid) occurance from geolocation_temp1 where event!='normal' group by driverid")

filter_drivers_nonnormal_events

  • As stated earlier about RDD transformations, select operation is a RDD transformation and therefore does not return anything.
  • The resulting table will have a count of total non-normal events associated with each driver. Register this filtered table as a temporary table so that subsequent SQL queries can be applied to it.
%spark
geolocation_temp2.registerTempTable("geolocation_temp2")

register_table

  • You can view the result by executing an action operation on the RDD.
%spark
geolocation_temp2.take(10).foreach(println)

Lab4_11

4.4.2 Perform join Operation

In this section we will perform a join operation geolocation_temp2 table has details of drivers and count of their respective non-normal events. drivermileage_temp1 table has details of total miles travelled by each driver.

  • We will join two tables on common column, which in our case is driverid.
%spark
val joined = hiveContext.sql("select a.driverid,a.occurance,b.totmiles from geolocation_temp2 a,drivermileage_temp1 b where a.driverid=b.driverid")

Lab4_12

  • The resulting data set will give us total miles and total non-normal events for a particular driver. Register this filtered table as a temporary table so that subsequent SQL queries can be applied to it.
%spark
joined.registerTempTable("joined")

register_join_table

  • You can view the result by executing action operation on RDD.
%spark
joined.take(10).foreach(println)

Lab4_13

4.4.3 Compute Driver Risk Factor

In this section we will associate a driver risk factor with every driver. Driver risk factor will be calculated by dividing total miles travelled by non-normal event occurrences.

%spark
val risk_factor_spark=hiveContext.sql("select driverid, occurance, totmiles, totmiles/occurance riskfactor from joined")

Lab4_14

  • The resulting data set will give us total miles and total non normal events and what is a risk for a particular driver. Register this filtered table as a temporary table so that subsequent SQL queries can be applied to it.
%spark
risk_factor_spark.registerTempTable("risk_factor_spark")
  • View the results
%spark
risk_factor_spark.take(10).foreach(println)

Lab4_15

Step 4.5: Load and Save Data into Hive as ORC

In this section we store data in a smart ORC (Optimized Row Columnar) format using Spark. ORC is a self-describing type-aware columnar file format designed for Hadoop workloads. It is optimized for large streaming reads and with integrated support for finding required rows fast. Storing data in a columnar format lets the reader read, decompress, and process only the values required for the current query. Because ORC files are type aware, the writer chooses the most appropriate encoding for the type and builds an internal index as the file is persisted.

Predicate pushdown uses those indexes to determine which stripes in a file need to be read for a particular query and the row indexes can narrow the search to a particular set of 10,000 rows. ORC supports the complete set of types in Hive, including the complex types: structs, lists, maps, and unions.

4.5.1 Create an ORC table

Create a table and store it as ORC. Specifying as orc at the end of the SQL statement below ensures that the Hive table is stored in the ORC format.

%spark
hiveContext.sql("create table finalresults( driverid String, occurance bigint,totmiles bigint,riskfactor double) stored as orc").toDF()

Note: toDF() creates a DataFrame with columns driverid String, occurance bigin, etc.

create_orc_table

4.5.2 Convert data into ORC table

Before we load the data into hive table that we created above, we will have to convert our data file into ORC format too.

Note: For Spark 1.4.1 and higher, use

%spark
risk_factor_spark.write.format("orc").save("risk_factor_spark")

If you used the above script, skip the following instruction and move to 4.5.3.

Note: For Spark 1.3.1, use

%spark
risk_factor_spark.saveAsOrcFile("risk_factor_spark")

risk_factor_orc

4.5.3 Load the data into Hive table using load data command

%spark
hiveContext.sql("load data inpath 'risk_factor_spark' into table finalresults")

load_data_to_finalresults

4.5.4 Verify Data Successfully Populated Hive Table by Spark (Check 1)

%spark
val riskfactor = hiveContext.sql("select * from finalresults")
riskfactor.registerTempTable("riskfactor")
riskfactor.take(10).foreach(println)

load_data_finalresults_table_lab4

Note: loads the first 10 rows from finalresults table

4.5.5 Verify Data Successfully Populated Hive Table in Hive (Check 2)

Execute a select query to verify your table has been successfully stored. You can go to Ambari Hive user view to check whether the Hive table you created has the data populated in it.

verify_table_populated

Hive finalresults table populated

Did both tables have the same data up to 10 rows?

Full Spark Code Review for Lab

Import hive and sql libraries

%spark
import org.apache.spark.sql.hive.orc._
import org.apache.spark.sql._

val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)

Shows tables in the default hive database

hiveContext.sql("show tables").collect.foreach(println)

Select all rows and columns from tables, stores hive script into variable
and registers variables as RDD

val geolocation_temp1 = hiveContext.sql("select * from geolocation")

val drivermileage_temp1 = hiveContext.sql("select * from drivermileage")

geolocation_temp1.registerTempTable("geolocation_temp1")
drivermileage_temp1.registerTempTable("drivermileage_temp1")

val geolocation_temp2 = hiveContext.sql("SELECT driverid, count(driverid) occurance from geolocation_temp1  where event!='normal' group by driverid")

geolocation_temp2.registerTempTable("geolocation_temp2")

Load first 10 rows from geolocation_temp2, which is the data from
drivermileage table

geolocation_temp2.take(10).foreach(println)

Create joined to join 2 tables by the same driverid and register joined
as a RDD

val joined = hiveContext.sql("select a.driverid,a.occurance,b.totmiles from geolocation_temp2 a,drivermileage_temp1 b where a.driverid=b.driverid")

joined.registerTempTable("joined")

Load first 10 rows and columns in joined

joined.take(10).foreach(println)

Initialize risk_factor_spark and register as an RDD

val risk_factor_spark=hiveContext.sql("select driverid, occurance, totmiles, totmiles/occurance riskfactor from joined")

risk_factor_spark.registerTempTable("risk_factor_spark")

Print the first 10 lines from the risk_factor_spark table

risk_factor_spark.take(10).foreach(println)

Create table finalresults in Hive, save it as ORC, load data into it,
print the first 10 lines from the Hive table in Spark

hiveContext.sql("create table finalresults( driverid String, occurance bigint,totmiles bigint,riskfactor double) stored as orc").toDF()

risk_factor_spark.write.format("orc").save("risk_factor_spark")

hiveContext.sql("load data inpath 'risk_factor_spark' into table finalresults")

val riskfactor = hiveContext.sql("select * from finalresults")

riskfactor.registerTempTable("riskfactor")

riskfactor.take(10).foreach(println)

Appendix A: Run Spark Code in the Spark Interactive Shell

1) Open your terminal or putty. SSH into the Sandbox using root as login and hadoop as password.

login: root
password: hadoop

Optionally, if you don’t have an SSH client installed and configured you can use the built-in web client which can be accessed from here: http://host:4200 (use the same username and password provided above)

2) Let’s enter the Spark interactive shell (spark repl). Type the command

spark-shell

This will load the default Spark Scala API.

spark_shell_welcome_page

Note: Hive comes preconfigured with HDP Sandbox.

The coding exercise we just went through can be also completed using a Spark shell. Just as we did in Zeppelin, you can copy and paste the code.

Summary

Congratulations! Let’s summarize the spark coding skills and knowledge we acquired to compute risk factor associated with every driver. Apache Spark is efficient for computation because of its in-memory data processing engine. We learned how to integrate hive with spark by creating a Hive Context. We used our existing data from Hive to create an RDD. We learned to perform RDD transformations and actions to create new datasets from existing RDDs. These new datasets include filtered, manipulated and processed data. After we computed risk factor, we learned to load and save data into Hive as ORC.

Suggested Readings

To learn more about Spark, checkout these resources:
Apache Spark
Apache Spark Welcome
Spark Programming Guide
Learning Spark
Advanced Analytics with Spark
HDP DEVELOPER: APACHE SPARK USING SCALA
HDP DEVELOPER: APACHE SPARK USING PYTHON

Lab 5 - Data Reporting With Zeppelin

Introduction

In this tutorial you will be introduced to Apache Zeppelin. In the earlier section of lab, you learned how to perform data visualization
using Excel. This section will teach you to visualize data using Zeppelin.

Pre-Requisites

The tutorial is a part of series of hands on tutorial to get you started on HDP using the Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial.

  • Hortonworks Sandbox
  • Learning the Ropes of the Hortonworks Sandbox
  • Lab 1: Load sensor data into HDFS
  • Lab 2: Data Manipulation with Apache Hive
  • Lab 3: Use Pig to compute Driver Risk Factor/ Lab 4: Use Spark to compute Driver Risk Factor
  • Working Zeppelin installation
  • Allow yourself approximately one hour to complete this tutorial.

Outline

Apache Zeppelin

Apache Zeppelin provides a powerful web-based notebook platform for data analysis and discovery.
Behind the scenes it supports Spark distributed contexts as well as other language bindings on top of Spark.

In this tutorial we will be using Apache Zeppelin to run SQL queries on our geolocation, trucks, and
riskfactor data that we’ve collected earlier and visualize the result through graphs and charts.

NOTE: We can also run queries via various interpreters for the following (but not limited to) spark, hawq and postgresql.

Step 6.1: Create a Zeppelin Notebook

1) Navigate to http://sandbox.hortonworks.com:9995 directly to open the Zeppelin interface.

Zeppelin Dashboard

2) Click on create note, name the notebook Driver Risk Factor and a new notebook shall get started.

Zeppelin Create New Notebook

Step 6.2: Execute a Hive Query

6.2.1 Visualize finalresults Data in Tabular Format

In the previous Spark and Pig tutorials you already created a table finalresults or riskfactor which gives the risk factor associated with every driver. We will use the data we generated in this table to visualize which drivers have the highest risk factor. We will use the jdbc hive interpreter to write queries in Zeppelin. jdbc by default runs hive.

1) Copy and paste the code below into your Zeppelin note.

%jbdc(hive)

SELECT * FROM riskfactor

2) Click the play button next to “ready” or “finished” to run the query in the Zeppelin notebook.
Alternative way to run query is “shift+enter.”

Initially, the query will produce the data in tabular format as shown in the screenshot.

play_button_zeppelin_workbook

Step 6.3: Build Charts using Zeppelin

6.3.1 Visualize finalresults Data in Chart Format

1. Iterate through each of the tabs that appear underneath the query.
Each one will display a different type of chart depending on the data that is returned in the query.

charts_tab_under_query_lab6

2. After clicking on a chart, we can view extra advanced settings to tailor the view of the data we want

Chart Advanced Settings

3. Click settings to open the advanced chart features.

4. To make a chart with riskfactor.driverid and riskfactor.riskfactor SUM, drag the table relations into the boxes as shown in the image below.

Advanced Settings Boxes

5. You should now see an image like the one below.

Bar Graph Example Image

6. If you hover on the peaks, each will give the driverid and riskfactor.

driverid_riskfactor_peak

7. Try experimenting with the different types of charts as well as dragging and
dropping the different table fields to see what kind of results you can obtain.

8. Let’ try a different query to find which cities and states contain the drivers with the highest riskfactors.

%jdbc

SELECT a.driverid, a.riskfactor, b.city, b.state
FROM riskfactor a, geolocation b where a.driverid=b.driverid

9. Run the query above using the keyboard shortcut Shift+Enter.
You should eventually end up with the results in a table below.

Filter City and States

10. After changing a few of the settings we can figure out which of the cities have the high risk factors.
Try changing the chart settings by clicking the scatterplot icon. Then make sure that the keys a.driverid
is within the xAxis field, a.riskfactor is in the yAxis field, and b.city is in the group field.
The chart should look similar to the following.

Scatter Plot Graph

The graph shows that driver id number A39 has a high risk factor of 652417 and drives in Santa Maria.

Summary

Now that we know how to use Apache Zeppelin to obtain and visualize our data, we can use the skills
we’ve learned from our Hive, Pig, and Spark labs, as well and apply them to new kinds of data to
try to make better sense and meaning from the numbers!

Suggested Readings