Friday, 19 June 2015

HBase POC

In this blog we shall discuss about a sample Proof of Concept for HBase.
Here we have a Data set as in the below image.
Sample_Hbase_Use_case
This data set consists of the details about the duration of total incoming calls, outgoing calls and the messages sent from a particular mobile number on a specific date.
The first field represents date, the second field represents mobile number, the third field represents the total duration of incoming calls, fourth field represents total duration of outgoing calls, and fifth field represents the total number of messages sent.
Now our task is to retrieve the information of the duration of incoming and outgoing calls and messages sent, from a phone number on a particular date.
In this use case, I am trying to filter the records of 15th March 2014. Here is an HBase Program to achieve this.
Below is the complete code of it.
public class sample {
            private static Configuration conf;
            static HTable table;
         public sample(String tableName, String colFams) throws IOException {
                        conf = HBaseConfiguration.create();
                        createTable(tableName, colFams);
                        table = new HTable(conf, tableName);
            }
            void createTable(String tableName, String colFams) throws IOException {
                        HBaseAdmin hbase = new HBaseAdmin(conf);
                        HTableDescriptor desc = new HTableDescriptor(tableName);
                        HColumnDescriptor meta = new HColumnDescriptor(colFams.getBytes());
                        desc.addFamily(meta);
                        hbase.createTable(desc);
            }
            public static void addColumnEntry(String tableName, String row,
                                    String colFamilyName, String colName, String values)
                                    throws IOException {
                        byte[] rowKey = Bytes.toBytes(row);
                        Put putdata = new Put(rowKey);
                        putdata.add(Bytes.toBytes(colFamilyName), Bytes.toBytes(colName),
                                                Bytes.toBytes(values));
                        table.put(putdata);
            }
            public static void getAllRecord(String tableName, String startPartialKey,
                                    String endPartialKey) throws IOException {
                        try {
                                    Scan s;
                                    if (startPartialKey == null || endPartialKey == null)
                                                s = new Scan();
                                    else
                                                s = new Scan(Bytes.toBytes(startPartialKey),
                                                                        Bytes.toBytes(endPartialKey));
                                    ResultScanner ss = table.getScanner(s);
                                  HashMap<String, HashMap<String, String>> outputRec = newHashMap<String, HashMap<String, String>>();
                                    String imsi = “”;
                                    for (Result r : ss) {
                                          HashMap<String, String> keyVal = new HashMap<String, String>();
                                                for (KeyValue kv : r.raw()) {
                                                      imsi = new String(kv.getRow()).substring(10);
                                                            keyVal.put(new String(kv.getQualifier()),
                                                                                 new String(kv.getValue()));
                                                            outputRec.put(imsi, keyVal);
                                                            if (keyVal.size() == 3)
                                                                 System.out.println(imsi + “\t” + “Incoming minutes:”
                                                                               + keyVal.get(“c1″) + “\t Outcoming minutes:”
                                                                               + keyVal.get(“c2″) + “\t Messages:”
                                                                                + keyVal.get(“c3″));
                                                }
                                    }
                        } finally {
                        }
            }
            public static void main(String[] args) throws IOException {
                        String tableName = “daterecords”;
                        String colFamilyNames = “i”;
                      sample test = new sample(tableName, colFamilyNames);
                        String fileName = “/home/cloudera/Desktop/data”;
                        // This will reference one line at a time
                        String line = null;
                        try {
                                    // FileReader reads text files in the default encoding.
                                    FileReader fileReader = new FileReader(fileName);
                                    // Always wrap FileReader in BufferedReader.
                                    BufferedReader bufferedReader = new BufferedReader(fileReader);
                                    while ((line = bufferedReader.readLine()) != null) {
                                                String[] values = line.split(“\t”);
                                                addColumnEntry(tableName, values[0] + “-” + values[1],
                                                                        colFamilyNames, “c1″, values[2]);
                                                addColumnEntry(tableName, values[0] + “-” + values[1],
                                                                        colFamilyNames, “c2″, values[3]);
                                                addColumnEntry(tableName, values[0] + “-” + values[1],
                                                                       colFamilyNames, “c3″, values[4]);
                                    }
                                    bufferedReader.close();
                        } catch (FileNotFoundException ex) {
                                    System.out.println(“Unable to open file ‘” + fileName + “‘”);
                        } catch (IOException ex) {
                                    System.out.println(“Error reading file ‘” + fileName + “‘”);
                                    // Or we could just do this:
                                    // ex.printStackTrace();
                        }
                        getAllRecord(tableName, “20140315″, “20140316″);
            }
}
Sample_HBase_Program_-_1
Here we have created an object of Configuration, HTable class and creating the Hbase Table with name: daterecords and the column family: i.
In this use case, we will be taking the combination of date and mobile number separated by ‘-‘ as row key for this Hbase table and the incoming , outgoing call durations’, the number of messages sent as the columns ‘c1’, ‘c2’, ‘c3’ for the column family ‘i’.
We have the input data stored in the local file system of Cloudera. So we need to write Java Logic that reads the data from the file.
Below is the Java logic.
IMG_21032014_190139
In this method we are storing the data into the table for each column of the column family.
We can check the data stored in Hbase table ‘daterecords’ by using the scan command.
You will receive the data as in the below image.
3
Now we have inserted the data in to the HBase Table successfully.
Let us retrieve the records stored in the Table of a Particular date.
In this use case
, we are trying to retrieve the records of the Date: 15th March 2014
To retrieve the records we have created a Method
getAllRecord(String tableName, String startPartialKey, String endPartialKey)
The First Parameter represents the table name, the second represents the start date from which we need to retrieve the data and the third one is the next date of start date.
E.g:
getAllRecord(tableName, “20140315″, “20140316″);
Now let us understand the logic of this method.
4
We are trying to scan the Hbase Table by Using HBase API with the help of startPartialKey and endPartialKey.
As StartPartialKey
and endPartialkey are not null
, it will go to else block and scan the records having the value of startPartialKey.
5
We have created an object of Result scanner which stores the scanned records of the Hbase table and a HashMap to store the output that will be result.
6
We are creating an object of Result to get the data store in the Result Scanner and executing a for loop.
imsi is the string that is defined to store the Mobile number and keyVal is a Hash Map that stores the output retrieved from the column of a particular phone.
We have given 20140315-1234567890 as the rowkey to the Hbase table. In this 20140315 represents the date and 1234567890 represents the Mobile number.
As we require only the mobile number we are using substring method to retrieve it.
We are retrieving the data from the r.raw() and storing it in the HashMap by using Put.
Finally we are trying to print them on the console.
The Output will be as in the below image.
7
We have successfully retrieved the records of the Date: 15th March 2014.

Thursday, 18 June 2015

Apache Spark (Part 2)

With the advent of new technologies, there has been an increase in the number of data sources. Web server logs, machine log files, user activity on social media, recording a user’s clicks on the website and many other data sources have caused an exponential growth of data. Individually this content may not be very large, but when taken across billions of users, it produces terabytes or petabytes of data. For example, Facebook is collecting 500 terabytes(TB) of data everyday with more than 950 million users. Such a massive amount of data which is not only structured but also unstructured and semi-structured  is considered under the roof known as Big Data.
Big data is of more importance today, because in past we collected a lot of data and built models to predict the future, called forecasting, but now we collect data and build models to predict what is happening now, called nowcasting. So a phenomenal amount of data is collected, but only a tiny amount is ever analysed. The term Data Science means deriving knowledge from big data, efficiently and intelligently.
The common tasks involved in data science are :
  1. Dig data to find useful data to analyse
  2. Clean and prepare that data
  3. Define a model
  4. Evaluate the model
  5. Repeat until we get statistically good results, and hence a good model
  6. Use this model for large scale data processing
MapReduce, the parallel data processing paradigm, greatly simplified the analysis of big data using large clusters of commodity hardware. But as big data got bigger, people wanted to mainly perform 2 types of tasks over it –
  1. More complex, multi-stage applications, like the iterative machine learning and graph algorithms
  2. More interactive ad-hoc queries
Map-Reduce is not good at either of them because they both need efficient mechanisms to share data between the multiple map-reduce stages. In map-reduce, the only way to share data across different stages is the distributed data storage which is very slow as it involves disk operations and data replication across the cluster. So in map-reduce, each step that we perform passes through the disk. The mappers reads data from the disk, processes it, and writes it back to the disk before shuffle operation. This data is then replicated across the cluster in order to provide fault tolerance. The reducers then read this data from the disk, processes it and writes it back to the disk. For iterative jobs, multiple map-reduce operations needs to be performed sequentially, which involves a very high disk I/O and high latency making them too slow. Similarly, for interactive queries, data is read from the disk each time the query is executed.
Capture
Capture1
Apache Spark
sparkApache Spark is an open source big data processing framework built to overcome the limitations from the traditional map-reduce solution. The main idea behind Spark is to provide a memory abstraction which allows us to efficiently share data across the different stages of a map-reduce job or provide in-memory data sharing.
Capture2
Capture3
At a high level, every Spark application consists of a driver program that runs the user’s main function and executes various parallel operations on the worker or processing nodes of the cluster. The main memory abstraction that spark provides is of a Resilient distributed dataset (RDD), which is a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel. RDDs can be created from a file in the file system, or an existing collection in the driver program, and transforming it. So as the name suggests, the data from a file in the file system or from an existing collection in the driver program that forms a RDD is partitioned and distributed across the worker or processing nodes in the cluster, thereby forming a distributed dataset.
The important point to remember is that RDDs are immutable distributed datasets across the cluster and are generated using the coarse grained operations i.e operations applied to the entire dataset at once. We can persist an RDD in-memory, allowing it to be reused efficiently across parallel operations or different stages of a map-reduce job. So the reason why spark works so well for iterative machine learning algorithms and interactive queries is that, instead of sharing data across different stages of the job by writing it to the disk (which involves disk I/O and replication across nodes) it caches the data to be shared in-memory which allows faster access to the same data.
For fault tolerance, spark automatically records how the RDD is created i.e the series of transformations applied to the base RDD to form a new RDD. So when the data is lost, it reapplies the steps from transformations graph to rebuilt the  RDD or lost data. Generally, only a piece of data is lost when a machine fails, and so RDD tracks the transformations at machine level and recomputes only the required operations or a part of transformations on the previous data to perform recovery.
Spark Ecosystem
Spark Ecosystem
Apache Spark takes map-reduce to the next level with it’s capabilities like in-memory data storage and near real-time data processing. In addition to the core APIs, spark has additional libraries integrated into it to support a variety of data analysis and machine learning algorithms.
1) GraphX – Graph computation engine which supports complex graph processing algorithms efficiently and with improved performance. PageRank Algorithm – a popular graph processing algorithm outperforms in apache spark environment over map-reduce.
2) MLLib – Machine learning library built on the top of spark and supports many complex machine learning algorithms which runs 100x faster than map-reduce.
3) Spark Streaming –  Supports analytical and interactive applications built on live streaming data.
4) Shark (SQL) – Used for querying structured data. Spark SQL allows the users to ETL their data from its current format (like JSON, Parquet, a Database), transform it, and expose it for ad-hoc querying.
This was a brief overview of Apache Spark, in future articles, we will dive deep into its concepts and programming model.

DIFFERENCES BETWEEN DISTRIBUTED COMPUTING AND HADOOP


                   Distributed Computing
                       Hadoop
1)      In Grid computing, date moves towards business logic i.e. data stored in a storage area network is accessed by a data node which has business logic to process that data.
      If the volume of data is very large then, the data node remains idle for a long time till it receives all data. If a data node fails while processing data, then then whole time taking retrieval process has to start again.

            In Hadoop, we have a concept called Data  Locality. Here, the business logic is moving  towards data i.e. if a particular data node fails during data processing, then a copy of its data will be available on some other node in the cluster and the same business logic operates on that copy of data.Which results in proper network  optimization.
2)      The programmer has to handle data flow along with data analysis. For ex: socket programming.                                    
.            Programmer needs to take care of only data  analysis, Data flow is handled by Hadoop  framework.
3)      Programmer has to write the code for handling node failure.
           Programmer need not handle node failure, the  name node i.e. master node will handle node  failure.
4)      Here, when a data node completes its computational task. It returns the output to the master node but does not maintain a copy of that output in its LFS (Local file System). If data lost in transit, then the data node has to again redo the task for the same request.
            In Hadoop, we have a concept called Data    Localization i.e. every Data node maintains a  copy of the output emitted in its LFS. So even  if data lost in transit, then the same output can  be sent again for the same request.
                                                                      

 To understand the first difference you can see the images given below: -

                                      1. Distributed Computing

                                      2. Hadoop Distributed System.

Thus, Hadoop is an open source, distributed ,batch-processing and fault-tolerant system used for storing and processing big data.

Batch processing systems execute a series of programs called jobs without any human intervention. these system are termed as batch processing because they collect input data in the form of batches or set of records and each batch is considered as a single unit of input data. The output is another batch which can be used for further computation.

Wednesday, 17 June 2015

Hadoop Basic Terms

Before knowing about Hadoop, we need to be aware about some basic terminologies: -

1) Node: - A computational resource which participates in a computational job by performing some
    computational tasks within a network is called node.

2) Cluster: - A group of nodes connected to each other through a common and dedicated network to form a distributed system is called cluster.

3) Hadoop node: - Any computational node which has both hadoop distributed file system (HDFS) and Map Reduce (MR) components in it is called as hadoop node.

4) Hadoop cluster: - A group of hadoop nodes connected to each other through a common and dedicated network is called as Hadoop Cluster. 

5) File System: - A file system is the underlying structure a computer uses to organize data on a hard disk.

Hadoop has two major components: -

1) HDFS

2) MAPREDUCE

    
                                                                        
                                                                     1) HDFS

HDFS stands for Hadoop Distributed file system, it is a shared file system used by by all the slave nodes of Hadoop distributed system. It is meant for Storage.

                                                                     2) MAPREDUCE

This component is used for data analysis. This component is implemented in Java programming language.

                                                                3) HADOOP CLUSTER


As seen in the cluster above, every computational node including the master node has two components: -
1) HDFS
2) MAPREDUCE

The main computational job is divided into a no of computational tasks and each task is handled by a slave node. In a hadoop cluster, the master node is called name node and all the slave nodes are called as data nodes. The name node is connected to all its data nodes through a common and dedicated network like VPN.

Saturday, 6 June 2015

Apache Spark

Hadoop, the data processing framework that’s become a platform unto itself, becomes even better when good components are connected to it. Some shortcomings of Hadoop, like MapReduce component of Hadoop have a reputation for being slow for real-time data analysis.
Enter Apache Spark, a Hadoop-based data processing engine designed for both batch and streaming workloads, now in its 1.0 version and outfitted with features that exemplify what kinds of work Hadoop is being pushed to include. Spark runs on top of existing Hadoop clusters to provide enhanced and additional functionality.
Let’s look at spark’s key features and how it works along with Hadoop

Apache Spark Key Benefits:

img2-R

Spark’s Awesome Features:

  • Hadoop Integration – Spark can work with files stored in HDFS.
  • Spark’s Interactive Shell – Spark is written in Scala, and has it’s own version of the Scala interpreter.
  • Spark’s Analytic Suite – Spark comes with tools for interactive query analysis, large-scale graph processing and analysis and real-time analysis.
  • Resilient Distributed Datasets (RDD’s) – RDD’s are distributed objects that can be cached in-memory, across a cluster of compute nodes. They are the primary data objects used in Spark.
  • Distributed Operators – Besides MapReduce, there are many other operators one can use on RDD’s.

 Advantages of Using Apache Spark with Hadoop:

img3-R
  • Apache Spark fits into the Hadoop open-source community, building on top of the Hadoop Distributed File System (HDFS). However, Spark is not tied to the two-stage MapReduce paradigm, and promises performance up to 100 times faster than Hadoop MapReduce for certain applications.
  • Well suited to machine learning algorithms – Spark provides primitives for in-memory cluster computing that allows user programs to load data into a cluster’s memory and query it repeatedly.
  • Run 100 times faster – Spark, analysis software can also speed jobs that run on the Hadoop data-processing platform. Dubbed the “Hadoop Swiss Army knife,” Apache Spark provides the ability to create data-analysis jobs that can run 100 times faster than those running on the standard Apache Hadoop MapReduce. MapReduce has been widely criticized as a bottleneck in Hadoop clusters because it executes jobs in batch mode, which means that real-time analysis of data is not possible.
  • Alternative to MapReduce -Spark provides an alternative to MapReduce. It executes jobs in short bursts of micro-batches that are five seconds or less apart. It also provides more stability than real-time, stream-oriented Hadoop frameworks such as Twitter Storm. The software can be used for a variety of jobs, such as an ongoing analysis of live data and thanks to a software library, more computationally in-depth jobs involving machine learning and graph processing.
  • Support for Multiple Languages – Using Spark, developers can write data-analysis jobs in Java, Scala or Python, using a set of more than 80 high-level operators.
  • Library Support – Spark’s libraries are designed to complement the types of processing jobs being explored more aggressively with the latest commercially supported deployments of Hadoop. MLlib implements a slew of common machine learning algorithms, such as naïve Bayesian classification or clustering; Spark Streaming enables high-speed processing of data ingested from multiple sources; and GraphX allows for computations on graph data.
  • Stable API – With the version 1.0, Apache Spark offers a stable API (application programming interface), which developers can use to interact with Spark though their own applications. This helps in using Storm more easily in Hadoop based deployment.
  • SPARK SQL Component – Spark SQL component for accessing structured data, allows the data to be interrogated alongside unstructured data in analysis work. Spark SQL, which is only in alpha at the moment, allows SQL-like queries to be run against data stored in Apache Hive. Extracting data from Hadoop via SQL queries is yet another variant of the real-time querying functionality springing up around Hadoop.
  • Apache Spark Compatibility with Hadoop [HDFS, HBASE and YARN] – Apache Spark is fully compatible with Hadoop’s Distributed File System (HDFS), as well as with other Hadoop components such as YARN (Yet Another Resource Negotiator) and the HBase distributed database.

Industry Adopters:

IT companies such as Cloudera, Pivotal, IBM, Intel and MapR have all folded Spark into their Hadoop stacks. Databricks, a company founded by some of the developers of Spark, offers commercial support for the software. Both Yahoo and NASA, among others, use the software for daily data operations.

Conclusion:

What Spark has to offer is bound to be a big draw for both users and commercial vendors of Hadoop. Users who are looking to implement Hadoop and who have already built many of their analytics systems around Hadoop are attracted to the idea of being able to use Hadoop as a real-time processing system.
Spark 1.0 provides them with another variety of functionality to support or build proprietary items around. In fact, one of the big three Hadoop vendors, Cloudera, has already been providing commercial support for Spark via its Cloudera Enterprise offering. Hortonworks has also been offering Spark as a component of its Hadoop distribution. The implementation of Spark on a large scale by top companies indicates its success and its potential when it comes to real-time processing.

Tuesday, 2 June 2015

Business Intelligence (BI)

What is Business Intelligence (BI)?

  •  Business Intelligence is a generalized term applied to a broad category of applications and technologies for gathering, storing, analyzing and providing access to data to help enterprise users make better business decisions
  • Business Intelligence applications include the activities of decision support systems, query and reporting, online analytical processing (OLAP), statistical analysis, forecasting, and data mining
  • An alternative way of describing BI is: the technology required to turn raw data into information to support decision-making within corporations and business processes


BusinessIntelligence Architecture overview
BusinessIntelligence Architecture



Business intelligence has become a critical element of information technology. It’s an old term with general or even ambiguous meaning. It has been used synonymously with decision support, analysis, and data warehousing, but today business intelligence has a more specific definition and a better understood application. Taken literally, business intelligence is just that—intelligence or understanding of your business. You get that understanding by analyzing your business operations.


This business intelligence process can deliver significant, bottom-line results. Implementing its technologies and applying its process can help make your business more effective and more efficient, increasing revenue, decreasing costs, and improving your relationships with customers and suppliers.

   Why BI?
  • BI technologies help bring decision-makers the data in a form they can quickly digest and apply to their decision making.
  • BI turns data into information for managers and executives and in general, people making decisions in a company.
  • Companies want to use technology tactically to make their operations more effective and more efficient - Business intelligence can be the catalyst for that efficiency and effectiveness.
By definition, the moment any given business is operating, it begins generating data. Some obvious examples are sales, bookkeeping, production data, warehouse information, transportation and logistics, personnel, etc.In addition there also exists large volumes of data which are important to the business but not directly generated by business operations. Examples are market data, competitive data, tenders and proposal, legal information, raw material prices, etc.

As such, none of the above described information can be used in its raw form by corporate management to make decisions although the information is critical in helping make those business decisions.Therein lies the necessity for Business Intelligence. BI technologies help bring decision-makers the data in a form they can quickly digest and apply to their decision making. BI turns data into information for managers and executives and in general, people making decisions in a company.

     Benefits:

 The benefits of a well-planned BI implementation are going to be closely tied to the business objectives driving the project.
  1. Identify trends and anomalies in business operations more quickly, allowing for more accurate and timelier decisions.
  2. Deliver actionable insight and information to the right place with less effort .
  3. Identify and operate based on a single version of the truth, allowing all analysis to be completed on a core foundation with confidence.