Friday, May 26, 2017

Apache Phoenix Bulk Loading

Here is an example:
Create us_population.sql file
CREATE TABLE IF NOT EXISTS us_population ( state CHAR(2) NOT NULL, city VARCHAR NOT NULL, population BIGINT CONSTRAINT my_pk PRIMARY KEY (state, city));
Create us_population.csv file
NY,New York,8143197 CA,Los Angeles,3844829 IL,Chicago,2842518 TX,Houston,2016582 PA,Philadelphia,1463281 AZ,Phoenix,1461575 TX,San Antonio,1256509 CA,San Diego,1255540 TX,Dallas,1213825 CA,San Jose,912332
Create us_population_queries.sql file
SELECT state as “State”,count(city) as “City Count”,sum(population) as “Population Sum” FROM us_population GROUP BY state ORDER BY sum(population) DESC;
Execute the following command from a command terminal
/opt//psql.py us_population.sql us_population.csv us_population_queries.sql
Output:
csv columns from database.
CSV Upsert complete. 10 rows upserted
Time: 0.181 sec(s)
St City Count Population Sum
-- ---------------------------------------- ----------------------------------------
NY 1 8143197
CA 3 6012701
TX 3 4486916
IL 1 2842518
PA 1 1463281
AZ 1 1461575
Time: 0.03 sec(s)
For more information click here.

HBASE Tools

Apache phoenix 

Apache phoenix is an SQL interface on the top of HBASE. For more information click here
You can connect by executing the following command under bin.
python sqlline.py zookeeper_url 
The Phoenix client driver can be found here. You can  download and setup SQuirrel as your SQL client so you can issue adhoc SQL against your HBase cluster

HBASE Stargate  

HBASE startgate is the rest interface of HBASE. for more information click here.

Apache Phoenix Bulk Loading 

Here is an example:
Create us_population.sql file
CREATE TABLE IF NOT EXISTS us_population ( state CHAR(2) NOT NULL, city VARCHAR NOT NULL, population BIGINT CONSTRAINT my_pk PRIMARY KEY (state, city));
Create us_population.csv file
NY,New York,8143197 CA,Los Angeles,3844829 IL,Chicago,2842518 TX,Houston,2016582 PA,Philadelphia,1463281 AZ,Phoenix,1461575 TX,San Antonio,1256509 CA,San Diego,1255540 TX,Dallas,1213825 CA,San Jose,912332
Create us_population_queries.sql file
SELECT state as “State”,count(city) as “City Count”,sum(population) as “Population Sum” FROM us_population GROUP BY state ORDER BY sum(population) DESC;
Execute the following command from a command terminal
/opt//psql.py us_population.sql us_population.csv us_population_queries.sql
Output:
csv columns from database.
CSV Upsert complete. 10 rows upserted
Time: 0.181 sec(s)
St City Count Population Sum
-- ---------------------------------------- ----------------------------------------
NY 1 8143197
CA 3 6012701
TX 3 4486916
IL 1 2842518
PA 1 1463281
AZ 1 1461575
Time: 0.03 sec(s)
For more information click here.

HBASE ImportTSV 

ImportTsv is a utility that will load data in TSV format into HBase. It can be used for the HBASE tables those are not managed by phoenix.
Please use this link for more information.

Enabling Jmx for Tomcat

Create (or append to) the file /opt/mas/tomcat/bin/setenv.sh
#!/bin/sh
CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote.port=1701 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false \
 -Dcom.sun.management.jmxremote.password.file=/opt/mas/jmx/tomcat.password -Dcom.sun.management.jmxremote.access.file=/opt/mas/jmx/jmx.access"
then run the following commands:
chown tomcat:tomcat /opt/mas/jmx/tomcat.password /opt/mas/tomcat/bin/setenv.sh
/etc/init.d/tomcat_8080 stop
/etc/init.d/tomcat_8080 start

Enable JMX metrics for Spark.

Steps to enable JMX metrics for Spark.

  1. For basic JVM metrics, append the following line to the file /etc/spark/conf.mas/spark-env.sh:
# Enable HistoryServer JMX connections on port 9991
HADOOP_JOB_HISTORYSERVER_OPTS="-Dcom.sun.management.jmxremote.port=9991 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/mas/jmx/mapred.password -Dcom.sun.management.jmxremote.access.file=/opt/mas/jmx/jmx.access"


  1. For Spark Mater webUI update spark-env.sh
           export SPARK_MASTER_WEBUI_PORT=18080
       3.   For more metrics update metrics.properties
*.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink
*.source.jvm.class=org.apache.spark.metrics.source.JvmSource

Wednesday, May 17, 2017

Configuring Zabbix Monitoring For All Hadoop Services (Zookeeper,Spark, namenode, datanode , job history server , hdfs journal node, hive and HBase)

Below info document Zabbix monitoring configuration for all Hadoop services like Zookeeper,Spark, namenode, datanode , job history server , hdfs journal node, hive and HBase with respect file changes.

For Zookeeper:
vi /etc/default/zookeeper
export SERVER_JVMFLAGS="-Dcom.sun.management.jmxremote.port=1703 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/zookeeper.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"
---------------------------------
Spark:
vi /etc/spark/conf/metrics.properties
*.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink
*.source.jvm.class=org.apache.spark.metrics.source.JvmSource
---------------------------------
For namenode, datanode and job history server and hdfs journal node:
vi /etc/hadoop/conf/hadoop-env.sh

# Use YARN for all hadoop commands
export HADOOP_MAPRED_HOME=/usr/lib/hadoop-mapreduce

# Enable NameNode JMX connections on port 9980
HADOOP_NAMENODE_OPTS="-Dcom.sun.management.jmxremote.port=9980 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/hdfs.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"

# Enable DateNode JMX connections on port 9981
HADOOP_DATANODE_OPTS="-Dcom.sun.management.jmxremote.port=9981 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/hdfs.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"

# Enable JournalNode JMX connections on port 1704
HADOOP_JOURNALNODE_OPTS="${HADOOP_JOURNALNODE_OPTS} -Dcom.sun.management.jmxremote.port=1704 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/hdfs.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"

# Enable Job History Server JMX connections on port 9991
HADOOP_JOB_HISTORYSERVER_OPTS="${HADOOP_JOB_HISTORYSERVER_OPTS} -Dcom.sun.management.jmxremote.port=9991 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/mapred.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"

----------------------------
For resourcemanager, nodemanager:
vi /etc/hadoop/conf/yarn-env.sh
YARN_RESOURCEMANAGER_OPTS="-Dcom.sun.management.jmxremote.port=9983 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/yarn.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"

YARN_NODEMANAGER_OPTS="-Dcom.sun.management.jmxremote.port=9984 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/yarn.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"
---------------------------------
For Hive

vi /etc/hive/conf/hive-env.sh
JMX_OPTS="-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/hive.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"
if [ "$SERVICE" = "hiveserver2" ]; then
  export HADOOP_OPTS="$HADOOP_OPTS $JMX_OPTS -Dcom.sun.management.jmxremote.port=1705 -Dproc_hiveserver"
elif [ "$SERVICE" = "metastore" ]; then
  export HADOOP_OPTS="$HADOOP_OPTS $JMX_OPTS -Dcom.sun.management.jmxremote.port=1706 -Dproc_metastore"
fi
----------------------------------
For HBase:

vi /etc/hbase/conf/hbase-env.sh
HBASE_JMX_BASE="-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.password.file=/opt/shekhar/jmx/hbase.password -Dcom.sun.management.jmxremote.access.file=/opt/shekhar/jmx/jmx.access"
export HBASE_MASTER_OPTS="$HBASE_MASTER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10101"
export HBASE_REGIONSERVER_OPTS="$HBASE_REGIONSERVER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10102"
export HBASE_THRIFT_OPTS="$HBASE_THRIFT_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10103"
#export HBASE_ZOOKEEPER_OPTS="$HBASE_ZOOKEEPER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10104"
export HBASE_REST_OPTS="$HBASE_REST_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10105"


Phoenix 4.7 integration issue with Spark 2.1.0

Steps to integrate Phoenix 4.7 with spark2.1.0
step 1. coping below files into /usr/lib/spark/lib
phoenix-core-4.7.0-HBase-1.0.jar
phoenix-server-4.7.0-HBase-1.0.jar
phoenix-spark-4.7.0-HBase-1.0.jar
phoenix-HBase-client.jar
Step2. creating soft links in /usr/lib/spark/lib
phoenix-HBase-client.jar -> /usr/lib/spark/lib/phoenix-server-client-4.7.0-HBase-1.0.jar
phoenix-spark-HBase.jar -> /usr/lib/spark/lib/phoenix-spark-4.7.0-HBase-1.0.jar
I had integration issue with jackson-core-XXX.jar files. As Spark 2.1 using 2.6.5 version of Jackson apis but Phonenix-Core using 1.9.13. phoneix-core module pom.xml having true so the output of MANIFEST file has below content and Class-Path configured with older version of jackson api and start getting exception like some of the methods not available. I solved the issue by removing true and building Phonenix-Core module then Class-path attribute not generated in Manifest file so it's started using Spark version of jars in run time.
Manifest file with true:
Manifest-Version: 1.0
Implementation-Title: Phoenix Core
Implementation-Version: 4.7.0-HBase-1.0
Archiver-Version: Plexus Archiver
Built-By: mas_user
Specification-Vendor: Apache Software Foundation
Specification-Title: Phoenix Core
Implementation-Vendor-Id: org.apache.phoenix
Class-Path: tephra-api-0.7.0.jar tephra-core-0.7.0.jar gson-2.2.4.jar
guice-3.0.jar javax.inject-1.jar aopalliance-1.0.jar guice-assistedin
ject-3.0.jar libthrift-0.9.0.jar fastutil-6.5.6.jar twill-common-0.6.
0-incubating.jar twill-core-0.6.0-incubating.jar twill-api-0.6.0-incu
bating.jar asm-all-5.0.2.jar twill-discovery-api-0.6.0-incubating.jar
twill-discovery-core-0.6.0-incubating.jar twill-zookeeper-0.6.0-incu
bating.jar metrics-core-3.1.0.jar tephra-hbase-compat-1.0-0.7.0.jar a
ntlr-3.5.jar ST4-4.0.7.jar antlr-runtime-3.5.jar stringtemplate-3.2.1
.jar antlr-2.7.7.jar jline-2.11.jar sqlline-1.1.8.jar guava-13.0.1.ja
r joda-time-1.6.jar annotations-1.3.2.jar jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar junit-4.12.jar hamcrest-core-1.3.jar p
rotobuf-java-2.5.0.jar httpclient-4.0.1.jar httpcore-4.0.1.jar common
s-logging-1.2.jar log4j-1.2.17.jar slf4j-api-1.6.4.jar snappy-0.3.jar
htrace-core-3.1.0-incubating.jar netty-all-4.0.23.Final.jar commons-
codec-1.7.jar commons-collections-3.2.1.jar commons-csv-1.0.jar jsr30
5-2.0.1.jar slf4j-log4j12-1.7.5.jar hadoop-auth-2.6.0-cdh5.4.8.jar ap
acheds-kerberos-codec-2.0.0-M15.jar apacheds-i18n-2.0.0-M15.jar api-a
sn1-api-1.0.0-M20.jar api-util-1.0.0-M20.jar curator-framework-2.7.1.
jar hadoop-core-2.6.0-mr1-cdh5.4.8.jar hsqldb-1.8.0.10.jar core-3.1.1
.jar hadoop-hdfs-2.6.0-cdh5.4.8.jar commons-daemon-1.0.13.jar leveldb
jni-all-1.8.jar hadoop-hdfs-2.6.0-cdh5.4.8-tests.jar findbugs-annotat
ions-1.3.9-1.jar jersey-client-1.9.jar commons-cli-1.2.jar commons-ma
th-2.1.jar commons-lang-2.6.jar hbase-common-1.0.0-cdh5.4.8.jar hbase
-annotations-1.0.0-cdh5.4.8.jar commons-io-2.4.jar jetty-util-6.1.26.
cloudera.4.jar hbase-protocol-1.0.0-cdh5.4.8.jar hbase-client-1.0.0-c
dh5.4.8.jar netty-3.6.6.Final.jar zookeeper-3.4.5-cdh5.4.8.jar jcodin
gs-1.0.8.jar hbase-server-1.0.0-cdh5.4.8.jar commons-httpclient-3.1.j
ar jersey-core-1.9.jar jersey-server-1.9.jar asm-3.1.jar jetty-6.1.26
.cloudera.4.jar jetty-sslengine-6.1.26.cloudera.4.jar jsp-2.1-6.1.14.
jar jsp-api-2.1-6.1.14.jar servlet-api-2.5-6.1.14.jar jasper-compiler
5.5.23.jar jasper-runtime-5.5.23.jar jamon-runtime-2.3.1.jar jersey
json-1.9.jar jettison-1.1.jar jaxb-impl-2.2.3-1.jar jaxb-api-2.1.jar
activation-1.1.jar hbase-server-1.0.0-cdh5.4.8-tests.jar hadoop-commo
n-2.6.0-cdh5.4.8.jar commons-math3-3.1.1.jar xmlenc-0.52.jar commons-
net-3.1.jar servlet-api-2.5.jar jsp-api-2.1.jar commons-el-1.0.jar je
ts3t-0.9.0.jar java-xmlbuilder-0.4.jar commons-configuration-1.6.jar
commons-digester-1.8.jar commons-beanutils-1.7.0.jar commons-beanutil
s-core-1.8.0.jar avro-1.7.6-cdh5.4.8.jar paranamer-2.3.jar jsch-0.1.4
2.jar curator-client-2.7.1.jar curator-recipes-2.7.1.jar htrace-core-
3.0.4.jar commons-compress-1.4.1.jar xz-1.0.jar hadoop-annotations-2.
6.0-cdh5.4.8.jar hadoop-mapreduce-client-core-2.6.0-cdh5.4.8.jar hado
op-yarn-common-2.6.0-cdh5.4.8.jar jersey-guice-1.9.jar guice-servlet-
3.0.jar hadoop-yarn-api-2.6.0-cdh5.4.8.jar joni-2.1.2.jar
Implementation-Vendor: Apache Software Foundation
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_65
Specification-Version: 4.7.0-HBase-1.0
Manifest file without true:
Manifest-Version: 1.0
Implementation-Title: Phoenix Core
Implementation-Version: 4.7.0-HBase-1.0
Archiver-Version: Plexus Archiver
Built-By: mas_user
Specification-Vendor: Apache Software Foundation
Specification-Title: Phoenix Core
Implementation-Vendor-Id: org.apache.phoenix
Implementation-Vendor: Apache Software Foundation
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_65
Specification-Version: 4.7.0-HBase-1.0
thanks,
Shekhar Reddy

Friday, February 17, 2017

How to upgrade Spark to 2.1.0

Step to upgrade Spark 2.1.0:

1. download required tag from https://github.com/apache/spark/tags and extract to spark folder
2. Go to spark folder and run below command
./dev/make-distribution.sh --name custom-spark --tgz -Pyarn -Phadoop-2.6 -Dhadoop.version=2.6.0-cdh5.4.8 -Dhbase.version=1.0.0-cdh5.4.8 -Dflume.version=1.5.0-cdh5.4.8 -Dzookeeper.version=3.4.5-cdh5.4.8 -Phive -Phive-thriftserver

3. output of above command is spark-2.1.0-bin-custom-spark.tgz
- copy spark-2.1.0-bin-custom-spark.tgz to /usr/lib/spark/ and extract and then delete spark-2.1.0-bin-custom-spark.tgz
scp -r root@:/spark_2.1.0/spark-2.1.0/shekhar/spark-2.1.0-bin-custom-spark.tgz /usr/lib/spark/.
tar xvzf spark-2.1.0-bin-custom-spark.tgz
rm -r spark-2.1.0-bin-custom-spark.tgz

(for backup) hdfs dfs -get /user/spark/share/lib /root/shekhar (spark:spark)

4. create soft likes
ln -s /var/run/spark/work /usr/lib/spark/work
ln -s /etc/spark/conf /etc/alternatives/spark-conf
ln -s /usr/lib/spark/jars /usr/lib/spark/lib

5. update /usr/lib/spark/bin/spark-submit
vi /usr/lib/spark/bin/spark-submit
export HADOOP_CONF_DIR=/etc/hadoop/conf
export YARN_CONF_DIR=/etc/yarn/conf

6. run below command
chmod -R 777 /tmp/hive
export JAVA_HOME=/usr/

Steps to create web service Producer(Using annatation and bean config) and Consuming webservice

Steps to create web service (Producer)

First down load the required jar files

a. Go to http://xfire.codehaus.org/Download
b. down load xfire-distribution-1.2.6.zip file
c. extract this and go to lib folder
d. And copy all jars to your application.


1.add xfire.xml file



2.configure org.codehaus.xfire.spring.remoting.XFireExporter








3.configure handler mapping





citationService.xfire




4.write proxy interface

TestInterface:
package com.optrasystems.mvc;
public interface TestInterface {
public String sayHello();
}

5.write a class with exposed methods

Test.java;

package com.optrasystems.mvc;
public class Test implements TestInterface{
public String sayHello(){

String string="old String";
return string;
}
}



Consuming above webservice
==========================
first generate the java file using wsdl file

select project right click ---> new -->other-->select "web service client" (in webservice) --->click on 'next' button -->provide wsdl path in 'service defination' input box and decrease valume type bar to 'Develop client'---> click on finish

1. using Xfire:

XFireClientFactoryBean client=new XFireClientFactoryBean();
try{
client.setServiceClass(Class.forName("com.optrasystems.mvc.TestInterface"));
client.setWsdlDocumentUrl("http://192.168.100.151:8089/thorlabs/app/citationService?WSDL");
client.afterPropertiesSet();
client.getObject();
TestInterface lTestInterface=(TestInterface)(client.getObject()));
String str=lTestInterface.sayHello();
request.getSession().setAttribute("webservice", str);
}catch(java.lang.Exception e){
e.printStackTrace();
}


==================================================
Creating web service using Spring Annatation

step 1: create proxy interface

@WebService
public interface PilotSystemWebservice {
//declare all exposed methods here.
}

step 2: create implementation class for the above interface

@WebService(serviceName="shekhar",endpointInterface="com.optrasystems.service.PilotSystemWebservice")
public class PilotSystemWebserviceImpl implements PilotSystemWebservice {
// implement all method.
}

step 3: add the following bean configuration to Spring context.








step4: WSDL file Url is
http://localhost:8089/thorlabs/app/services/shekhar?wsdl

thorlads : application name
app : url-pattern of DispatcherServlet configured in web.xml
services: constant url for all ,this sanded url provided by Spring
shekhar :service name provided in Interface( serviceName="shekhar")


step 5: client will be same(above one) for this application

How to write and use Hive UDAF

How to Write Hive UDAF:

1. Create Java class which extends org.apache.hadoop.hive.ql.exec.hive.UDAF;
    2. Create Inner Class which implements UDAFEvaluator
    3. Implement five methods ()
init() – The init() method initializes the evaluator and resets its internal state. We are using new Column() in code below to indicate that no values have been aggregated yet.
iterate() – this method is called every time there is anew value to be aggregated. The evaluator should update its internal state with the result of performing the aggregation (we are doing sum – see below). We return true to indicate that input was valid.
terminatePartial() – this method is called when Hive wants a result for the partial aggregation. The method must return an object that encapsulates the state of the aggregation.
merge() – this method is called when Hive decides to combine one partial aggregation with another.
terminate() – this method is called when the final result of the aggregation is needed.
    4. Compile and Package JAR
    5. CREATE TEMPORARY FUNCTION in hive CLI
    6. Run Aggregation Query – Verify Output!!!

package org.hardik.letsdobigdata;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.hardik.letsdobigdata.MeanUDAF.MeanUDAFEvaluator.Column;

@Description(name = "Mean", value = "_FUNC(double) - computes mean", extended = "select col1, MeanFunc(value) from table group by col1;")
public class MeanUDAF extends UDAF {

// Define Logging
static final Log LOG = LogFactory.getLog(MeanUDAF.class.getName());

public static class MeanUDAFEvaluator implements UDAFEvaluator {

/**
 * Use Column class to serialize intermediate computation
 * This is our groupByColumn
 */
public static class Column {
 double sum = 0;
 int count = 0;
 }

private Column col = null;

public MeanUDAFEvaluator() {
 super();
 init();
 }
// A - Initalize evaluator - indicating that no values have been
 // aggregated yet.

public void init() {
 LOG.debug("Initializeuator");
 col = new Column();
 }

// B- Iterate every time there is a new value to be aggregated
 public boolean iterate(double value) throws HiveException {
 LOG.debug("Iterating each value for aggregation");
 if (col == null)
 throw new HiveException("Item is not initialized");
 col.sum = col.sum + value;
 col.count = col.count + 1;
 return true;
 }
// C - Called when Hive wants partially aggregated results.
 public Column terminatePartial() {
 LOG.debug("Returnially aggregated results");
 return col;
 }
 // D - Called when Hive decides to combine one partial aggregation with another
 public boolean merge(Column other) {
 LOG.debug("mergingombining partial aggregation");
 if(other == null) {
 return true;
 }
 col.sum += other.sum;
 col.count += other.count;
 return true;
}
 // E - Called when the final result of the aggregation needed.
 public double terminate(){
 LOG.debug("Attend of last record of the group - returning final result");
 return col.sum/col.count;
 }

 }
}

CREATE TABLE IF NOT EXISTS orders (order_id int, order_date string, customer_id int, amount int) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' STORED AS TEXTFILE;

LOAD DATA LOCAL INPATH '/root/utaf.txt' INTO TABLE orders;

101,2016-01-01,7,3540
102,2016-03-01,1,240
103,2016-03-02,6,2340
104,2016-02-12,3,5000
105,2016-02-12,3,5500
106,2016-02-14,9,3005
107,2016-02-14,1,20
108,2016-02-29,2,2000
109,2016-02-29,3,2500
110,2016-02-27,1,200


add jar /root/HiveUDFs-master-0.0.1-SNAPSHOT.jar;
CREATE TEMPORARY FUNCTION MeanFunc AS 'org.hardik.letsdobigdata.MeanUDAF';

select customer_id, MeanFunc(amount) from orders group by customer_id;

Hive UDF and UDAF Example

How to write UDF function in Hive?

    1. Create Java class for User Defined Function which extends ora.apache.hadoop.hive.sq.exec.UDF amd implement more than one evaluate() methods and put your desisred logic and you are almost there.
    2. Package your Java class into JAR file (I am using maven)
    3. Go to Hive CLI – ADD your JAR, verify your JARs in Hive CLI classpath
    4. CREATE TEMPORARY FUNCTION in hive which points to your Java class
    5. Use it in Hive SQL and have fun!


package org.hardik.letsdobigdata;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

public class Strip extends UDF {

private Text result = new Text();
 public Text evaluate(Text str, String stripChars) {
 if(str == null) {
 return null;
 }
 result.set(StringUtils.strip(str.toString(), stripChars));
 return result;
 }
 public Text evaluate(Text str) {
 if(str == null) {
 return null;
 }
 result.set(StringUtils.strip(str.toString()));
 return result;
 }
}


ADD JAR /root/HiveUDFs-master-0.0.1-SNAPSHOT.jar;
list jars;
CREATE TEMPORARY FUNCTION STRIP AS 'org.hardik.letsdobigdata.Strip';
CREATE TABLE IF NOT EXISTS dummy (Value1 VARCHAR(64), Value2 VARCHAR(64)) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' STORED AS TEXTFILE;
LOAD DATA LOCAL INPATH '/root/ajay.txt' INTO TABLE dummy;

select strip('hadoop','ha') from dummy;

OK
_c0
doop
doop
Time taken: 0.148 seconds, Fetched: 2 row(s)

How to use Hive Bucket Example

How does Hive distribute the rows across the buckets? In general, the bucket number is determined by the expression hash_function(bucketing_column) mod num_buckets. (There's a '0x7FFFFFFF in there too, but that's not that important). The hash_function depends on the type of the bucketing column. For an int, it's easy, hash_int(i) == i. For example, if user_id were an int, and there were 10 buckets, we would expect all user_id's that end in 0 to be in bucket 1, all user_id's that end in a 1 to be in bucket 2, etc. For other datatypes, it's a little tricky. In particular, the hash of a BIGINT is not the same as the BIGINT. And the hash of a string or a complex datatype will be some number that's derived from the value, but not anything humanly-recognizable. For example, if user_id were a STRING, then the user_id's in bucket 1 would probably not end in 0. In general, distributing rows based on the hash will give you a even distribution in the buckets.

set hive.mapred.mode=unstrict; -  to access partitioned table without where condition
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.exec.max.dynamic.partitions.pernode=1000;
set hive.enforce.bucketing = true;

DROP TABLE IF EXISTS temp_user;
CREATE TEMPORARY TABLE temp_user(
firstname VARCHAR(64),
lastname VARCHAR(64),
address STRING,
country VARCHAR(64),
city VARCHAR(64),
state VARCHAR(64),
post STRING,
phone1 VARCHAR(64),
phone2 STRING,
email STRING,
web STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';

vi /root/data_hive.csv
Rebbecca,Didio,171 E 24th St,AU,Leith,TA,7315,03-8174-9123,0458-665-290,rebbecca.didio@didio.com.au,http://www.brandtjonathanfesq.com.au
Stevie,Hallo,22222 Acoma St,AU,Proston,QL,4613,07-9997-3366,0497-622-620,stevie.hallo@hotmail.com,http://www.landrumtemporaryservices.com.au
Mariko,Stayer,534 Schoenborn St #51,AU,Hamel,WA,6215,08-5558-9019,0427-885-282,mariko_stayer@hotmail.com,http://www.inabinetmacreesq.com.au
Gerardo,Woodka,69206 Jackson Ave,AU,Talmalmo,NS,2640,02-6044-4682,0443-795-912,gerardo_woodka@hotmail.com,http://www.morrisdowningsherred.com.au
Chun,Richrdson,3 Aiea Heights #660,CA,Regina,SK,S4T 3L1,306-245-2534,306-697-2337,chun_richrdson@richrdson.org,http://www.hoytrobertfesq.com
Lelia,Thiemann,440 Town Center Dr,CA,Kamloops,BC,V2B 7W6,250-671-3851,250-798-7786,lelia.thiemann@yahoo.com,http://www.kleemandenaaesq.com
Cordell,Zinda,91 Argyle Rd,CA,Sherbrooke,QC,J1H 6E3,819-508-6057,819-313-7350,cordell_zinda@cox.net,http://www.kayejeffreyaesq.com
Dorothy,Aitken,4 Hanover Pike,CA,Mississauga,ON,L5V 1E5,905-554-3838,905-355-9556,dorothy.aitken@cox.net,http://www.mcmillonwendyaesq.com
Nobuko,Halsey,8139 I Hwy 10 #92,US,New Bedford,MA,2745,508-855-9887,508-897-7916,nobuko.halsey@yahoo.com,http://www.goemanwoodproductsinc.com
Lavonna,Wolny,5 Cabot Rd,US,Mc Lean,VA,22102,703-483-1970,703-892-2914,lavonna.wolny@hotmail.com,http://www.linhareskennethaesq.com
Lashaunda,Lizama,3387 Ryan Dr,US,Hanover,MD,21076,410-678-2473,410-912-6032,llizama@cox.net,http://www.earnhardtprinting.com
Mariann,Bilden,3125 Packer Ave #9851,US,Austin,TX,78753,512-223-4791,512-742-1149,mariann.bilden@aol.com,http://www.hpgindustrysinc.com


LOAD DATA LOCAL INPATH '/root/data_hive.csv' INTO TABLE temp_user;
DROP TABLE IF EXISTS bucketed_user;
CREATE TABLE bucketed_user(
firstname VARCHAR(64),
lastname VARCHAR(64),
address STRING,
city VARCHAR(64),
state VARCHAR(64),
post STRING,
phone1 VARCHAR(64),
phone2 STRING,
email STRING,
web STRING
) COMMENT 'A bucketed sorted user table' PARTITIONED BY (country VARCHAR(64)) CLUSTERED BY (state) SORTED BY (city) INTO 32 BUCKETS STORED AS TEXTFILE;

set hive.enforce.bucketing = true;
INSERT OVERWRITE TABLE bucketed_user PARTITION (country) SELECT firstname ,lastname , address , city , state , post , phone1 , phone2 , email , web , country FROM temp_user;

Wednesday, November 16, 2016

Hive Filter to skip .tmp files while quering

1. Create class implements PathFilter
package com.hivefilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
public class FileFilterExcludeTmpFiles implements PathFilter {
        public boolean accept(Path p) {
                String name = p.getName();
                return !name.startsWith("_") && !name.startsWith(".") &&!name.endsWith(".tmp");
        }
}

2. Create jar file and Copyjar /usr/lib/hive/lib location and add below property in /etc/hive/conf/hive-site.xml file.

 
          mapred.input.pathFilter.class
          com.alu.spm.hivefilter.FileFilterExcludeTmpFiles

Creating Hive UDF and Using it


Create class and extend UDF

package com;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.serde2.io.DoubleWritable;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.Text;

public class TestUDF extends UDF {

public TestUDF(){
}
 public Text evaluate(Text str)  {
     return new Text(str.toString().toUpperCase());
 }
}


1. Create jar
jar cvf test.jar com/TestUDF.class
2. move jar to hdfs
hdfs dfs -put /home/cloudera/workspace/training/test.jar /user/hive/udf/.
hdfs dfs -chmod 777  /user/hive/udf/test.jar
3. create UDF
create function my_upper2(string) returns string location '/user/hive/udf/test.jar' symbol='com.TestUDF';
4. use UDF
select my_upper2(name) from table1