Sunday, May 21, 2017

Hive JDBC in Cloudera Hadoop


I am going to stick with Cloudera Quickstart VM, which saves me a lot of time on buggy messy configuration. Now I try to bridge the gap between Hive and unstructured data by JDBC. Forget python. Java is the native language in Hadoop.

1. install hive jdbc driver

$ sudo yum install hive-jdbc  # red-hat
Add /usr/lib/hive/lib/*.jar and /usr/lib/hadoop/*.jarto classpath.

2 write java codes

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;

public class etl {
       private static String driverName = "org.apache.hive.jdbc.HiveDriver";
       public static void main(String[] args) throws SQLException {
    try {Class.forName(driverName);}
    catch(ClassNotFoundException ex) {
       System.out.println("Error: unable to load driver class!");
       System.exit(1);
    }    
          // get connection, user and password are ignored in non-secured mode
          Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "cloudera", "cloudera");
          Statement stmt = con.createStatement();
       // execute statement
          ResultSet res = stmt.executeQuery("SELECT * FROM employee ");
          System.out.println("Result:");
          System.out.println(" ID \t Name \t Salary \t Designation  ");
          while (res.next()) {
             System.out.println(res.getInt(1) + " " + res.getString(2) + " " + res.getDouble(3) + " " + res.getString(4));
          }
          con.close();
       }
    }
notes:
  1. driverName is for hiveServer2. the previous version has longer driver name.
  2. table employee is prepared as in my previous blog or https://www.tutorialspoint.com/hive/
  3. connection is “jdbc:hive2://localhost:10000/default”, username and password can be empty string.
  4. Java class ResultSet is weird and quite different from Python cursor. It provides a getter methods such as getInt, getString, getDouble and requires a column index numbered from 1. This means the strict data type enforcement. The nextmethod moves the object cursor to the next row so a while loop can iterate through the result set.

3. compile and run

This is the most buggy part. I saw in StackOverflow, someone suggest run it as:
javac -cp . etl.class
java -cp . etl
But no matter how I tried(change configuration here and there, tinker codes here and there), I always got java - ClassNotFoundException. I guess the reason is that the Java compiler or JVM doesn’t read classpath as supposed.
Fortunately, I got a friend studying PhD in Hadoop. He simply use IDE to add classpath instead of writing classpath in bashrc. To be more specific:
  1. eclipse -new -> new java project -> build java path, add external JARs
  2. local at /usr/lib/hive/lib/*.jar, add all JARs
  3. run as application

mySQL

This is another topic. I will keep it here in case I will need in the future.
brew install mysql
We've installed your MySQL database without a root password. To secure it run:
    mysql_secure_installation

MySQL is configured to only allow connections from localhost by default

To connect run:
    mysql -uroot

To have launch start mysql now and restart at login:
  brew services start mysql
Or, if you don't want/need a background service you can just run:
  mysql.server start
==> Summary
🍺  /usr/local/Cellar/mysql/5.7.18_1: 321 files, 234.5MB
​

Hive Python API installation in RedHat

cloudera quickstart vm is based on Centos, a free version of Redhat distribution. What you can get from a free meal is some basic stuff for a quick demo. The syntax of Hive is pretty similar to normal SQL, but the problem is how to efficiently transform real world data to organized structure so you can feed them into Hadoop world. You will have to use general purpose languages such as python and java to cleanse the unstructured data.

install sublime

The default text editor vi is so ugly and difficult to use. Let’s go sublime.
download at www.sublimetext.com/3 go for the tarball besides Ubuntu 64 bit. It’s only 9 MB.
cd Downloads
tar -vxjf sublime_text_xxx.tar.bz2
nano .bash_profile   # add next line, save and exit
alias subl="~/Downloads/sublime_text_3/sublime_text"
source .bash_profile # load bash script
subl  # enjoy!
Note that Centos shell doesn’t automatically source bash_profile when open. Go edit -> profile preference -> title -> check “login shell”.

show module path in 3 ways

python -c 'import sys; print "\n".join(sys.path)'  #show class path
pip show numpy # show path for a specific class/module
import numpy
help(numpy)
I quickly find out how anaconda accommodate each module, e.g.:
anaconda/envs/py3/lib/python3.6/site-packages/matplotlib/pyplot.py

python API: PyHive

I first tried to upgrade the access to “express” to “enterprise” and add anaconda parcel in the cloudera manager. But my computer becomes extremely slow and conda command still doesn’t work.
My 2nd attempt is sudo yum install -y python27 because the default python is outdated 2.6 version which is abandoned by pandas. But I couldn’t figure out where the python2.7 was installed. Then I download python 2.7 source tgz from official: https://www.python.org/downloads/release/python-2713/
sudo mv ~/Downloads/Python-2.7.13.tgz /usr/src
cd /usr/src
sudo tar xzf Python-2.7.13.tgz
cd Python-2.7.13.tgz
sudo ./configure
sudo make altinstall # not replace default /usr/bin/python
which python2.7
But I realized I have to use anaconda to manage the modules because I couldn’t get any useful things done with them. So comes my 3rd solution:anaconda: https://docs.continuum.io/anaconda/install-linux
Note: download the python 2.7 version because:
  1. pyhive require python 2.7
  2. virtual env deosn’t work well in Centos
cd Downloads
bash Anaconda **.sh
... will be installed at /home/cloudera/Anaconda2
Prepending PATH=/home/cloudera/Downloads/enter/bin to PATH in /home/cloudera/.bashrc
A backup will be made to: /home/cloudera/.bashrc-anaconda2.bak
# exit shell and reopen
which python
conda install pyhive, thrift
conda install -c blaze sasl=0.2.1
conda install -c conda-forge thrift_sasl=0.2.1
Sadly, the hidden caveat is the missing of something called “GLIBC 2.14”. What’s more PyHive seems to be built for hiveServer but not hiveServer2.

python API: pyhs2

Then I planned to try https://github.com/BradRuderman/pyhs2 Although the author stopped maintaince 3 years ago, this module works amazingly.
still need anaconda python 2.7
sudo yum install gcc-c++ python-devel.x86_64 cyrus-sasl-devel.x86_64
sudo pip install pyhs2
minimum viable code:
import pyhs2
conn = pyhs2.connect(host='localhost',port=10000,
               authMechanism="PLAIN",user='cloudera',
               password='cloudera',database='default')
cur = conn.cursor()
print cur.getDatabases() # Show databases

cur.execute("select * from employee") # Execute query
print cur.getSchema() # Return column info from query

#Fetch table results
for i in cur.fetch():
    print i
Note that the table employee is prepared as in https://www.tutorialspoint.com
You can do it in hive command line or CDH hue.
create table
create table if not exists employee (eid int, name String, salary string, destination string)
comment 'Employee details'
row format delimited
fields terminated by '\t'
lines terminated by '\n'
stored as textfile;
The table is stored at (HDFS) \user\hive\warehouse
prepare data in sample.txt file:
1201    Gopal   45000   Technical manager
1202    Manisha 45000   Proof reader
1203    Masthanvali     40000   Technical writer
1204    Kiran   40000   Hr Admin
1205    Kranthi 30000   Op Admin
load data
load data local inpath
'/home/cloudera/Downloads/sample.txt' overwrite into table employee;
table metadata operation
show tables;
show tables '.*s';  --table end with 's',java regex
describe employee; -- show list of columns
alter table employee rename personnel; 
alter table employee add columns (age int);

set hive.cli.print.header=true;
select * from employee limit 10;

python API: impyla

install
sudo pip install impyla
sudo pip install thrift==0.9.3
try
from impala.dbapi import connect
conn = connect(host='localhost', port=21050)
cursor = conn.cursor()
print conn
cursor.execute('show tables;')
print cursor.description  # prints the result set's schema
results = cursor.fetchall()
The codes runs without error. But it doesn’t connect to the right database. Maybe there is some database connection catch somewhere.

Last catch

I realize python APIs don’t perform well (execute speed, documentation, community support, etc) because the native language of Hadoop is Java. So my next stop is JDBC.
​

Saturday, May 20, 2017

Hadoop Hive, local setup

I have spent many hours to get hive run locally in MacOS but couldn’t make it. Last time I get to the very end of this tutorial except the last step. This time I proceed a little further but bugs keep poping up:
$ hdfs dfs -mkdir /user
Cannot create directory /user. Name node is in safe mode.
$ hdfs dfsadmin -safemode leave
Safe mode is OFF
$ hdfs dfsadmin -safemode get
Safe mode is ON
Anyway, I try to record every step of my journey.
According to Quora, the minimum requirement for a local machine is 500 GB. This may be reason I failed.

Download tar files from respective official sites:
  1. oracle Java SE
  2. hadoop: http://hadoop.apache.org/releases.html
  3. hive
  4. derby

bash command line refresh

export varname=value  # export a variable to environment
env  # disply all environment variables, note that different shells have different default env variables
cat .bash_profile  # see a file in command window
less .bash_profile  # another way to see, less overwhelming
echo $varname # display variable value, note the dollar sign
eval $fun  # evaluate function
history  # display command history
hash     # display command history and path
pwd  # equal to echo $PWD which is a buit-in variable
let arg1=2  # define variable value, space is forbidden
let arg2=$arg1**3
echo $arg2
printf "result=%d\n" $arg2
Most compiler/commands are stored at /usr/local/bin .

path setup

# setup environment for hadoop
export HADOOP_HOME=/usr/local/hadoop-2.8.0    
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native 
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin

# setup environment for hive
export HIVE_HOME=/usr/local/apache-hive-2.1.1-bin 
export PATH=$PATH:$HIVE_HOME/bin
export CLASSPATH=$CLASSPATH:/usr/local/hadoop-2.8.0/lib/*:.
export CLASSPATH=$CLASSPATH:/usr/local/hive-2.1.1/lib*:.

# setup environment for Derby
export DERBY_HOME=/usr/local/db-derby-10.13.1.1-bin
export PATH=$PATH:$DERBY_HOME/bin:$HIVE_HOME/bin
export CLASSPATH=$CLASSPATH:$DERBY_HOME/lib/derby.jar:$DERBY_HOME/lib/derbytools.jar

hadoop initialize and commands

cd /usr/local/hadoop-2.8.0/
hdfs namenode -format
sbin/start-dfs.sh   # start Hadoop file system
# open http://localhost:50070/  
sbin/start-yarn.sh
# open http://localhost:8088/  

hadoop fs -mkdir /tmp 
hadoop fs -mkdir -p ~/hive/warehouse #also make pararent dir 
hadoop fs -chmod 777 /user  # change permission of file or folder
hdfs dfs -mkdir /user/hadoop  # make folder
hdfs dfs -put a.csv /user/hadoop/a.csv # move from local to HDFS
hdfs dfs -ls /user/hadoop  # list content of a folder
hdfs dfs -du  /user/hadoop/  # display utilization (size)
hdfs dfs -get /user/hadoop/ /home/ # get from HDFS to local
hdfs dfs -cp /user/hadoop/folderA /user/hadoop/folderB # copy
hdfs fs -rm -r <directory>  # remove

Hive metastore_db initialize

schematool -initSchema -dbType derby # may fail
mv metastore_db metastore_db.tmp #
schematool -initSchema -dbType derby #rerun
hive
show tables;
create table myGod (name string);
hive metastore configuration
add follows to hive-site.xml
<property> 
<name>system:java.io.tmpdir</name> 
<value>/usr/local/apache-hive-2.1.1-bin /iotmp</value> 
<description/> 
</property>
Hive use Derty database as default. You may change it to mySQL database by following the above link.
​

Sunday, May 14, 2017

Hadoop Hive setup by Cloudera quickstart


For beginners of Hadoop and Hive, a good starting point is to use Cloudera quickstart. Because the tricky configuration and overwhelming warning may scare off beginners. Steps:
  1. Download virtual box.
  2. Download cloudera quickstart vm at https://www.cloudera.com/downloads/
  3. use import .ovf file for setup. I was stupid to try the manual setup.
  4. start the vm.
  5. In the pop-up firefox browser, go through quickstart.cloudera tutorial to get yourself familiar with popular Hadoop framework/tools/concepts: Hue, Hive, file browser, sqoop, impala, parquet
Following is my learning notes for the tutorial

1, Ingest and Query Relational Data

Use Apache Sqoop to load relational data from MySQL into HDFS. With a few additional parameters, the relational data can be ready to be queried by Impala with Hadoop optimized file format Apache Avro.
sqoop import-all-tables \    -m 1 \    --connect jdbc:mysql://quickstart:3306/retail_db \    
--username=retail_dba \    --password=cloudera \    
--compression-codec=snappy \    
--as-parquetfile \    
--warehouse-dir=/user/hive/warehouse \    
--hive-import
It is launching MapReduce jobs to pull the data from our MySQL database and write the data to HDFS, distributed across the cluster in Apache Parquet format. Parquet is a format designed for analytical applications on Hadoop. Instead of grouping your data into rows like typical data formats, it groups your data into columns. This is ideal for many analytical queries where instead of retrieving data from specific records.
Hue provides a web-based interface for many of the tools in CDH with address: quickstart.cloudera:8888. In the QuickStart VM, the administrator username for Hue is ‘cloudera’ and the password is ‘cloudera’.
we told Sqoop to import the data into Hive but used Impala to query the data. This is because Hive and Impala can share both data files and the table metadata. Hive works by compiling SQL queries into MapReduce jobs, which makes it very flexible, whereas Impala executes queries itself and is built from the ground up to be as fast as possible, which makes it better for interactive analysis. We’ll use Hive later for an ETL (extract-transform-load) workload.
Simply put, Hive aims for compatibility and Impala aims for speed.

2, Correlate Structured Data with Unstructured Data

use hive to parse the unstructured log data and use impala to query.First create a table by parsing data using regular expression
CREATE EXTERNAL TABLE intermediate_access_logs (    ip STRING,    date STRING,    method STRING,    url STRING,    http_version STRING,    code1 STRING,    code2 STRING,    dash STRING,    user_agent STRING) ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.RegexSerDe'WITH SERDEPROPERTIES ('input.regex' = '([^ ]*) - - \\[([^\\]]*)\\] "([^\ ]*) ([^\ ]*) ([^\ ]*)" (\\d*) (\\d*) "([^"]*)" "([^"]*)"',    'output.format.string' = "%1$$s %2$$s %3$$s %4$$s %5$$s %6$$s %7$$s %8$$s %9$$s") LOCATION '/user/hive/warehouse/original_access_logs';
create another table, and then
INSERT OVERWRITE TABLE tokenized_access_logs SELECT * FROM intermediate_access_logs;
This does MapReduce job. You will get a table with 160 k records.Once it is ready, we can use impala to do the query:
select count(*),url from tokenized_access_logswhere url like '%\/product\/%'group by url order by count(*) desc;
Then analyze why some products are viewed most but don’t have a good sale.

3. Relationship strength analytics using Spark

The tool in CDH best suited for quick analytics on object relationships is Apache Spark.

4. Explore Log Events Interactively

learned how to use Cloudera Search to allow exploration of data in real time, using Flume and Solr and Morphlines

5. Hue Dashboard for data visualization

The plot is relatively simple. Maybe because it’s a free version.

short history of Hadoop

  • In March 2013 Intel invested $740 million in Cloudera for an 18% investment. Intel shared its roadmap with Cloudera so Cloudera could develop the software to maximize the chip performance. With cash piled from other investors by selling equity, Cloudera is able to acquire other company when necessary.
  • super evangelical to do a technology education project in order to win early customers.
  • nobody buys a database because it is easy to manage. people buy applications. They have important business or mission or operational problem to solve.So they buy the software that allows a non-programmer to do the job. That requires applications tools systems integrated together stack on top of the database.
  • Since the mid-1980s that dynamic is very much alive in this ecosystem. People bring existing skills to this new platform. BI, data analytics report, machine learning that you can never do that before but you can do it now.
  • banks, hospital, retail stores take security very seriously. If you break into a yahoo cluster steal a new story, who cares? Break into a bank’s big data platform, steal some transaction data that’s a big issue.
  • the question is ill-formed. Open source is a distribution model, license model, a development model but not a business model. You can’t build the long-term sustainable pure open-source business. Open source project often gets acquired by big company which has other revenue stream.
  • my competitors will tell you that I’m a furious guy that’s trying to lock our customers in because of my evil desires on their wallets. I suspect so. I’ve heard rumors. I am trying to lock IBM out. We will always have proprietary IP at Cloudera.
  • Who can afford to hire the thousands of smart people around the world working on this thing(open source)? No single company can compete with that. And we get the benefit.
  • plan to IPO. Cloudera was just traded at NYSE as CLDR on 2017.4.28, with IPO price at $18.

A New Generation Of Data Scientists

  • Most of the time I don’t do the fancy data visualization as in Sci-fi. I do data cleansing, prepare for the dataset.
  • big data economics: no individual record is particularly valuable. Having every record is incredibly valuable.
  • google file system: 4 kB per block. HDFS: 64/256 MB per block.
  • here’s a bunch of data and find me some insights. This is the worst thing can happen to me. I would say to the business person: tell me the problem you have. In the process of solving problem, we will discover the insights. Insights don’t come from vacuum. Insights come from interesting meaningful problems.
  • Have a data science team. Nobody is good at all the skills. You have to know every part and talk to everybody in the team.
  • we have to have skills not only analyzing data, but also deploy model in production system. Being data scientist involves some of the skills in DevOps.
  • Don’t solve the problem once. Solve it zero or solve it with multiple models. So choose the good problem first.
  • It’s never the case that we are trying to optimize a single thing in a data science problem. Like in an Ad prediction model, it’s not only use machine learning model to predict the click, but how to increase the revenue.
  • be self. iterate until awesome.
  • Hadoop developer training, hive and pig training, intro to data science (end to end problem-solving). recommendation system is in every field.

some terminology

ETL(Extract, Transform, Load): a repeatable programmed data movement
Extract: get data from source, is the most resource intensive
Transform: filter/map/enrich/combine/validate/sort, most difficult
Load: store data in a data warehouse or data mart.
Apache Spark was a cluster-computing framework, released in 2014.5.30 to address the limitation in the MapReduce cluster computing paradigm, which is a linear data flow structure. Spark provides a data structure called resilient distributed dataset (RDD), which facilliates the iterative algorithms of data access and data analysis.
Hive is not designed for online transaction processing. It is best used for traditional data warehousing tasks.
​