Wednesday, 18 March 2015

HADOOP VS SPARK




      HADOOP
  1. HDFS – Hadoop Distributed Filesystem. It is the distributed block-oriented non-updatable highly-scalable filesystem capable of running on the clusters of commodity hardware. It is a standalone tool and can be used without any other ecosystem components (except by Zookeeper and Journal Manager if you want your HDFS to be highly available, but it is a different story);
  2. MapReduce Framework – a basic framework for distributed computing on a cluster of commodity hardware. You are not obligated to work only with HDFS – filesystem is pluggable. You are also not obligated to use YARN with it: you can replace it with Mesos, for instance – resource manager is also pluggable;
  3. YARN – the default resource manager for Apache Hadoop cluster. But again, you can run the cluster without YARN by starting your MR jobs under Mesos or just running HBase which does not require YARN for running;
  4. Hive – SQL-like query engine on top of MapReduce framework that is capable of translating the HiveQL queries in a series of MapReduce jobs running on the cluster. But again, you are not obligated to use HDFS as a storage and you are not obligated to use MapReduce framework which in this case can be replaced with Tez;
  5. HBase – key-value store on top of HDFS that delivers the OLTP capabilities to Hadoop. The only dependencies for HBase are HDFS and Zookeeper. But is HDFS really dependency for HBase? No, it can also run on top of the Tachyon (in-memory filesystem), MapRFS, IBM GPFS and others.
  6. And that’s all. You might also consider Storm for processing streams of data, but it is completely independent from Hadoop and can run separately. You can also mention Mahoutfor machine learning on top of MapReduce, but it is continuously loosing community attention within the last year.
SPARK
  1. Spark Core – an engine for general-purpose distributed data processing. It has no dependencies and can run on any cluster of the commodity servers;
  2. Spark SQL – SQL query language on top of Spark, supporting a subset of SQL functionality and HiveQL. Not mature enough to be used in production systems. HiveQL integration requires Hive Metastore and Hive jar libraries;
  3. Spark Streaming – micro-batch data processing engine on top of Spark, supporting data ingestion from a variety of the source systems. The only dependency is Spark Core engine;
  4. MLlib – machine learning library built on top of Spark supporting range of data mining algorithms.
And let’s also cover one important myth about the Spark – “Spark is in-memory technology”. Spark is not an in-memory technology. It is pipelined execution engine, and it will write the data to disks during “shuffle” (if you need to aggregate data based on some field, for instance) and will spill in case it does not have enough memory (this can be tuned). So Spark is faster than MapReduce mostly because of its pipelining capabilities and not because of some cool “in-memory” optimizations. Of course, it has in-memory caching that improves the performance, but it is not the main reason why Spark is working fast.
Now let’s see the whole picture.
  1. MapReduce can be replaced with Spark Core. Yes, it can be replaced over the time and this replacement seems reasonable. But Spark is not yet mature enough to make a full replacement of this technology. Plus no one will completely give up on MapReduce unless all the tools that depend on it will support an alternative execution engine. For instance, there are some works running to support Pig scripts execution on top of Spark;    
     
  1. Hive can be replaced with Spark SQL. Yes, it is again true. But you should understand that Spark SQL is even younger than the Spark itself, this technology is younger than 1yo. At the moment it can only toy around the mature Hive technology, I will look back at this in 1.5 – 2 years. As you remember, 2-3 years ago Impala was the Hive killer, but now both technologies are living together and Impala still didn’t kill Hive.
  2. Storm can be replaced with Spark Streaming. Yes, it can, but to be fair Storm is not a piece of Hadoop ecosystem as it is completely independent tool. They are targeting a bit different computational models so I don’t think that Storm will disappear, but it will continue to leave as a niche product;
  3. Mahout can be replaced with MLlib. To be fair, Mahout is already losing the market and over the last year it became obvious that this tool will soon be dropped from the market. And here you can really say that Spark replaced something from Hadoop ecosystem.


Tuesday, 17 March 2015

UseCases of IOT and BIGDATA


Many of the conversations taking place around the Internet of Things (IoT) are incomplete without a mention of big data. Connected devices, sensors, and algorithms all operate in ways that involve massive amounts of data.
"The success or failure of the Internet of Things hinges on big data," says Brian Hopkins, an analyst with Forrester Research.
As organizations step into IoT, they must understand the symbiotic relationship between it and big data. For IoT deployments to really make an impact, they must provide some sort of useful tool or service, while also collecting relevant data.
Just like with any big-data play, merely collecting the data isn't enough. The data must be processed and analyzed to glean insights, and those insights must drive actionable steps that can improve the business.
Here are ten examples of IoT and big data working well together to provide analysis and insight.
1. UPS
One of the largest shipping companies in the world, UPS, has been using sensor data and big-data analytics to save money, improve efficiency, and lessen its environmental impact. UPS uses sensors on its delivery vehicles to monitor speed, miles per gallon, mileage, number of stops, and engine health.
According to an infographic released by UPS, the sensors capture more than 200 data points for each vehicle in a fleet of more than 80,000 every day. These help the company reduce idling time, fuel consumption, and harmful emissions.
Another way UPS is using big data is through its project ORION, which stands for On-Road Integrated Optimization and Navigation. The tool uses hundreds of millions of address data points, plus other data collected on the deliveries, to optimize delivery routes for efficiency. UPS plans to roll out ORION to all North American routes by 2017.
2. Barcelona, Spain
Barcelona is no stranger to technological innovation. The city hosts the Mobile World Congresstechnology show every year, but is also becoming a center for innovation itself.
The city offers smart parking meters that operate on city-wide wi-fi, giving residents real-time updates on where to park and allowing them to pay with their phone. Smart bus-stops provide passengers with real-time updates via touch-screen panels, and a city-wide sensor network informs workers and residents about temperature, air quality, noise level, and pedestrian traffic.
To manage all of this, Barcelona built a big-data system on Microsoft Azure to process and analyze the myriad data points it was receiving. With the insights generated by the system, the city can offer better services such as public transportation, plan for events like the La MercĂ© Festival more efficiently, and better understand the impact of tourism.
3. Virgin Atlantic
Virgin Atlantic has embraced IoT with a slew of connected Boeing 787 aircraft and connected cargo devices. Each plane has multiple internet-connected parts generating a large volume of data.
According to Virgin Atlantic IT director David Bulman, speaking to Computerworld UK, each connected flight can produce more than a half a terabyte of data. While the exact big data program isn't fully realized, the data could be used to predict maintenance requirements or to improve flight and fuel efficiency.
4. John Deere
Big data and the IoT are making waves in big agriculture, and one of the leaders in this area is equipment manufacturer John Deere. The John Deere Field Connect system monitors moisture levels and sends the data over a wireless connection for farmers to see. According to the website, the environmental sensors also measure "air and soil temperature, wind speed, humidity, solar radiation, rainfall and leaf wetness."
The data will help farmers discover when crops are reaching optimum moisture levels. Armed with this information, farmers can make timely irrigation decisions. Trend data can also show how much the change in seasons affects moisture retention.
5. TempuTech
TempuTech is another IoT and big data system that is impacting the agriculture industry. The company offers connected systems that monitor optimal grain storage and potential hazards in systems such as grain elevators.
Hazards such as broken belts or bearings can be monitored. Gain management systems show the moisture and temperature in grain bins, allowing aeration and fan settings to be manually altered to compensate. This data is also sent to farm operators, who can use it to predict moisture and temperature changes based on changes in weather.
6. Disney World MagicBand
Famous for the $1 billion investment it took to get off the ground, Disney World's proprietary MagicBand is a great example of IoT and big data working together. The MagicBand is a wearable, sensor-laden, wristband that vacationers use to do everything from check into their hotel room, buy their lunch, go through the turnstiles at the amusement parks, and reserve a spot for specific attractions.
Wearers use the band to 'check in' at certain posts by tapping it against a receiver, and it tracks their movement via RFID, so Disney collects data on visitor movement throughout the park. Leveraging this data, Disney can accommodate more guests, properly staff rides and attractions, and better regulate inventory at highly-trafficked shops and restaurants.
7. Alex and Ani
Jewelry store chain Alex and Ani have rolled out bluetooth sensors to their stores that can track traffic numbers in their stores and push specialized, or more customized, offers to users' phones as they enter the store.
The company has also partnered with beacon technology company Swirl to complete the deployment. The technology tracks customers movements within the store, similar to a heat map, so the company will be able to better organize and display its products to drive sales.
8. Clermont-Ferrand University Hospital
The Clermont-Ferrand University Hospital in France has deployed an IoT and big data initiative by partnering with Microsoft and Capsule Technologie. The hospital built a proprietary system to collect and organize data that is secure and compliant, and uses connected medical devices to transmit more data to the system.
After the nurses authenticate on a mobile app, they can send patient data directly from their medical devices and tools. The hospital has a fuller, more robust data set and the medical professionals can collect more data in less time, making their jobs easier.
9. King's Hawaiian
IoT and big data have also had a big impact in manufacturing and food production. Food company King's Hawaiian partnered with Rockwell Automation to implement connected machines in their bread production factories that allowed employees to monitor factory performance. The data collected allowed the company to reduce potential downtime of machines and lower maintenance costs.
10. BC Hydro
Headquartered in the Canadian province of British Columbia, BC Hydro is an electric utility providing power to nearly 2 million Canadian residents. In 2011, the company began upgrading its electricity meters to smart meters.
Users can now track their energy use by the hour and see trends in their own usage data. Electricity theft has been greatly reduced and automatic outage detection alerts the company when the power is out in a certain area. Leveraging the data collected, BC Hydro can provide improved service at a lower cost.

Project Ideas.



1) Read the Twitter Feed with a account and get the Realtime tweets for a particular Tag , say for example 
-I want to read the complete tweets with a hastag #WorldCup2015 or #58thGrammy
-want to count how many of them are media and how many of them are text
-Any additional tags involved in the text
-think of any additional ways to organize this information 
-also you can customize based on the location

in the above example #WorldCup2015 is just a parameter that needs to be passed from a GUI or some excel spreadsheet , Like wise you can change all the Parameter to your wish and get the information 

Monday, 16 March 2015

Hive Efficient Queries and Joins In Hive

HIVE Efficient Queries and JOINS OPTIMIZATION 

For Efficient Queries:

 In real time we will query lot of data to mining the important pattern which results in Improving the business.We always come across lot of problems in optimizing the jobs.
To optimize the Job we have to concrete on Mainly below things.
1)Data Layout (Partitions and Buckets) 
2)Data Sampling (Bucket and Block sampling)  and 3)Data Processing (Bucket Map Join and Parallel execution)
1    Partitions on Hive tables : We have to observe on which part of our table will undergo for search. So,on that columns it is good to create partitions which stops MR job to launch for scanning entire file.
      Bucketing Hive Tables: We can optimize joins by bucketing ‘similar’ IDs so Hive can minimise the processing steps, and reduce the data needed to parse and compare for join operations.
Bucket Sampling: We often want to query large table joins for a sample. We may want to try out complex queries or explore the data, and we want to do this iteratively, swiftly, and not process the whole data set. This is particularly difficult because of the joining of the tables since only very little data may overlap on independent samples from two tables. Ideally we would want to sample the relevant data on both tables and join it, i.e. ensure that we sample the same itinerary IDs from both tables and not sets with no or little overlap. The bucketing on the join column enables us to join specific buckets from two tables with data overlapping on the join column. Effectively, we execute exactly one part of the complete join operation and only incur the cost of it. The hashing function on the ID has the additional benefit of a (somewhat) random nature providing a representative sample.
Block Sampling:   Block sampling provides a powerful syntax to define various ways of sampling the data in a table with the TABLE SAMPLE statement. We can use it to sample a certain percentage, number of bytes, or rows of the data. We can use the sampling to approximate information like average distance between origin and destination of our itineraries. A query using 1% of the data using TABLE SAMPLE(1 PERCENT) on a large table will give us a near perfect answer and use up to only a hundredth of the resource and return the result one to two magnitudes faster.
Parallel Execution: Hadoop can execute map reduce jobs in parallel and several queries executed on Hive make automatically use of this parallelism. However, single, complex Hive queries commonly are translated to a number of map reduce jobs that are executed by default sequentially. Often though some of a query’s map reduce stages are not interdependent and could be executed in parallel. They then can take advantage of spare capacity on a cluster and improve cluster utilization while at the same time reduce the overall query executions time. The configuration in Hive to change this behavior is a merely switching a single flag SET hive.exce.parallel=true;.

DISTRIBUTE BY…SORT BY v. ORDER BY

In Hive, ORDER BY is not a very fast operation because it forces all the data to go into the same reducer node. By doing this, Hive ensures that the entire dataset is totally ordered.
However, sometimes we do not require total ordering. For example, suppose you have a table called user_action_table where each row has user_id, action, and time. Your goal is to order them by time per user_id.
If you are doing this with ORDER BY, you would run
SELECT time,user_id,action FROM user_action_table ORDER BY user_id,time
However, you can achieve the same result with
SELECT time,user_id,action FROM user_action_table DISTRIBUTE BY user_id SORT BY time
This is because all the rows belonging to the same user_id go to the same reducer (“DISTRIBUTE BY user_id”) and in each reducer, rows are sorted by time (“SORT BY time”). This is faster than the other query because it uses multiple reducers as opposed to a single reducer.
 JOINS OPTIMIZATION 
Hive, like other SQL databases, allows users to join various tables. Joins; however, can be computationally expensive, especially on big tables, and that’s precisely why they deserve an entire tip of their own!
1
2
hive> CREATE TABLE t1 (id INT, name STRING, age INT);
hive> CREATE TABLE t2 (id INT, name STRING, age INT);
A join query on the above tables would look like:
1
2
3
4
5
6
7
8
9
hive> SELECT
            t1.id,
            t1.name,
            t1.age,
            t2.name,
            t2.age
          FROM
            t1
            JOIN t2 ON (t1.id = t2.id)
We will now enumerate some of the best practices to use when performing joins in Hive.

Equity Joins
Hive only supports equality joins. This is primarily because it’s rather difficult to express non-equality join conditions in MapReduce.
Stream Table(Largest table last)
The earlier example shows an inner join between two tables. Given that inner joins are commutative; however, should the user prefer having t1 as the left table and t2 as the right table or vice-versa? The answer to this question lies in understanding how Hive compiles a join query to MapReduce. In the MapReduce job for regular inner joins, mappers run on both tables, emitting out records from that need to be joined by evaluating any UDFs in the query and filtering out any records based on the where clause. Then the shuffle phase is run which “shuffles” the keys based on the join key (idin above example). Subsequently, in the reduce phase, essentially a cross-product takes place between records from each table that have the same join key. During this reduce phase, records from all tables but the last table (in the join query) are buffered in memory while the records from query’s last table are streamed into the reducer. Consequently, in order to reduce the memory required by reducers, it’s recommended to put the largest tables last to ensure their records are streamed into the reducers.
Figure 1: Common Join in Hive
Alternatively, you can specify a hint in your query about which table to stream. In the above example, if t1 is larger than t2, your query the hint for streaming t1 would look like:

1
2
3
4
5
6
7
8
9
10
hive> SELECT
            /*+ STREAMTABLE(t1) */
            t1.id,
            t1.name,
            t1.age,
            t2.name,
            t2.age
          FROM
            t1
            JOIN t2 ON (t1.id = t2.id)
MAP Joins
If one of the tables in the join query is small enough to fit in memory, we recommend you to use map join. Map join is a special type of join where the smaller table is loaded in memory and the join is performed in the map phase of the MapReduce job. Since no reducers are required, map joins are much faster compared to regular joins.
In the above example, if t1 is small enough to fit in memory, the map join query would look like:

1
2
3
4
5
6
7
8
9
10
hive> SELECT
            /*+ MAPJOIN(t1) */
            t1.id,
            t1.name,
            t1.age,
            t2.name,
            t2.age
          FROM
            t1
            JOIN t2 ON (t1.id = t2.id)
Starting Hive 0.7, there is no need to specify the query hint (i.e. /*+ MAPJOIN(t1) */) for map joins. Set the hive.auto.convert.join property to true in hive-site.xml or your Hive CLI session, and Hive will use a conditional task to determine if it is possible to run a map join instead of a regular join. If so, it will run a map-join; if not, a regular join is run.
There are many topics related to Hive joins like bucketed and sort-merge joins, left semi joins, deciding between what goes in the “in” clause and what goes in the “where” clause of an outer join query.
More Elaborated Way.(Thru Diagrams)
Using the Distributed Cache
Hive-1641 solves this scaling problem. The basic idea of optimization is to create a new MapReduce local task just before the original join MapReduce task. This new task reads the small table data from HDFS to an in-memory hash table. After reading, it serializes the in-memory hash table into a hashtable file. In the next stage, when the MapReduce task is launching, it uploads this hashtable file to the Hadoop distributed cache, which populates these files to each mapper's local disk. So all the mappers can load this persistent hashtable file back into memory and do the join work as before. The execution flow of the optimized map join is shown in figure 2. After optimization, the small table needs to be read just once. Also if multiple mappers are running on the same machine, the distributed cache only needs to push one copy of the hashtable file to this machine. 

Figure 2: The Optimized Map Join 
Since map join is faster than the common join, it's better to run the map join whenever possible. Previously, Hive users needed to give a hint in the query to specify the small table. For example, select /*+mapjoin(a)*/ * from src1 x join src2 y on x.key=y.key;.

This isn't a good user experience because sometimes the user may give the wrong hint or may not give any hint at all. It's much better to convert the common join into a map join without user hints.

Converting Joins to Map Joins Based on Size
Hive-1642 solves this problem by converting the common join into a map join automatically. For the map join, the query processor should know which input table is the big table. The other input tables are recognized as the small tables during the execution stage, and these tables need to be held in the memory. However, in general, the query processor has no idea of input file size during compilation time because some of the tables may be intermediate tables generated from sub-queries. So the query processor can only figure out the input file size during the execution time.

Figure 3: The Join Execution Flow

As shown in figure 3, the left side flow shows the previous common join execution flow, which is very straightforward. On the other side, the right side flow is the new common join execution flow. During compilation time, the query processor generates a conditional task containing a list of tasks; one of these tasks gets resolved to run during execution time. First, the original common join task should be put into the task list. Then the query processor generates a series of map join tasks by assuming each of the input tables may be the big table. For example, select * from src1 x join src2y on x.key=y.key. Because both tables src2 and src1 can be the big table, the processor generates two map join tasks, with one assuming src1 is the big table and the other assuming src2 is the big table.

During the execution stage, the conditional task knows the exact file size of each input table, even if the table is an intermediate one. If all the tables are too large to be converted into map join, then just run the common join task as previously. If one of the tables is large and others are small enough to run map join, then the conditional task will pick the corresponding map join local task to run. By this mechanism, it can convert the common join into a map join automatically and dynamically.

Currently, if the total size of small tables is larger than 25MB, then the conditional task will choose the original common join to run. 25MB is a very conservative number and you can change this number with set hive.smalltable.filesize.



Machine Learning Task Mahout Currently Implements

Building a recommendation engine

Mahout currently provides tools for building a recommendation engine through the Taste library — a fast and flexible engine for CF. Taste supports both user-based and item-based recommendations and comes with many choices for making recommendations, as well as interfaces for you to define your own. Taste consists of five primary components that work with Users, Items and Preferences:
·         DataModel: Storage for Users, Items, and Preferences
·         UserSimilarity: Interface defining the similarity between two users
·         ItemSimilarity: Interface defining the similarity between two items
·         Recommender: Interface for providing recommendations
·         UserNeighborhood: Interface for computing a neighborhood of similar users that can then be used by the Recommenders

These components and their implementations make it possible to build out complex recommendation systems for either real-time-based recommendations or offline recommendations. Real-time-based recommendations often can handle only a few thousand users, whereas offline recommendations can scale much higher. Taste even comes with tools for leveraging Hadoop to calculate recommendations offline. In many cases, this is a reasonable approach that allows you to meet the demands of a large system with a lot of users, items, and preferences.


Clustering with Mahout

Mahout supports several clustering-algorithm implementations, all written in Map-Reduce, each with its own set of goals and criteria:
·         Canopy: A fast clustering algorithm often used to create initial seeds for other clustering algorithms.
·         k-Means (and fuzzy k-Means): Clusters items into k clusters based on the distance the items are from the centroid, or center, of the previous iteration.
·         Mean-Shift: Algorithm that does not require any a priori knowledge about the number of clusters and can produce arbitrarily shaped clusters.
·         Dirichlet: Clusters based on the mixing of many probabilistic models giving it the advantage that it doesn't need to commit to a particular view of the clusters prematurely.
From a practical standpoint, the names and implementations aren't as important as the results they produce. With that in mind, I'll show how k-Means works and leave the others for you to explore. Keep in mind that each algorithm has its own needs for making it run efficiently.
In outline (with more details to follow), the steps involved in clustering data using Mahout are:
1.    Prepare the input. If clustering text, you need to convert the text to a numeric representation.
2.    Run the clustering algorithm of choice using one of the many Hadoop-ready driver programs available in Mahout.
3.    Evaluate the results.
4.    Iterate if necessary.



Categorizing content with Mahout

Mahout currently supports two related approaches to categorizing/classifying content based on bayesian statistics. The first approach is a simple Map-Reduce-enabled Naive Bayes classifier. Naive Bayes classifiers are known to be fast and fairly accurate, despite their very simple (and often incorrect) assumptions about the data being completely independent. Naive Bayes classifiers often break down when the size of the training examples per class are not balanced or when the data is not independent enough. The second approach, called Complementary Naive Bayes, tries to correct some of the problems with the Naive Bayes approach while still maintaining its simplicity and speed. However, for this article, I'll show only the Naive Bayes approach, because it demonstrates the overall problem and inputs in Mahout.