Search This Blog

Tuesday, 25 March 2025

pig scripts

 first create  people_data.txt file

Alice,30,New York Bob,25,California Charlie,35,Texas David,30,California Eva,20,New York Frank,40,California Grace,30,Texas Hannah,45,New York Ivy,25,California Jack,20,Texas

--------------------------


copy data to hadoop directory


> hadoop fs -put people_data.txt people_data.txt

---------------------------------------


write pig script


pig1.pig


people= LOAD 'people_data.txt' USING PigStorage(',')as (name:chararray, age:int, city:chararray);


dump people;

-------------------------------------------
-----------------------------------------
pig2.pig

people= LOAD 'people_data.txt' USING PigStorage(',')as (name:chararray, age:int, city:chararray);

filtered_data = FILTER people BY age > 30;

dump filtered_data;
-----------------------------------------------------------

pig3.pig


people= LOAD 'people_data.txt' USING PigStorage(',')as (name:chararray, age:int, city:chararray);

Group_data = GROUP people by city;

dump Group_data;


----------------------------------------------------

pig4.pig

people= LOAD 'people_data.txt' USING PigStorage(',')as (name:chararray, age:int, city:chararray);

sort_age = ORDER people BY age DESC;

dump sort_age;

--------------------------------------------------------

pig5.pig

people_data.txt:

sql
John, 30, New York Alice, 25, Los Angeles Bob, 35, Chicago Charlie, 28, New York

city_data.txt:

sql
New York, 8000000, New York Los Angeles, 4000000, California Chicago, 2700000, Illinois San Francisco, 870000, California

Now, let's perform the join on the city field.

Pig Script:

pig
-- Load the people data people = LOAD 'people_data.txt' USING PigStorage(',') AS (name:chararray, age:int, city:chararray); -- Load the city data city_data = LOAD 'city_data.txt' USING PigStorage(',') AS (city:chararray, population:int, state:chararray); -- Perform the join on the 'city' field joined_data = JOIN people BY city, city_data BY city; -- Display the result of the join DUMP joined_data;


----------------------------------




Monday, 24 March 2025

HIVE LAB

 HIVE LAB

---------------------

1. create data base

hive > CREATE DATABASE db1;


2. show data bases

hive> show databases;


3. drop data base

hive> drop database db1;


4. show data bases

hive> show databases;


5.create database and alter database owner


hive > create database db1;


hive>ALTER DATABASE db1 SET DBPROPERTIES ('owner'='John');


6. create emp table in db1 as below

HIVE> create database db1;

hive > use db1;


hive> CREATE TABLE employees (

  emp_id INT,

  emp_name STRING,

  emp_age INT,

  emp_city STRING,

  emp_dept STRING,

  emp_sal  INT

)

row format delimited

fields terminated by ','

lines terminated by '\n'

stored as textfile;


$cat > employees.txt

101,scott,34,chennai,hr,45000

102,lara,32,bangalore,fin,55000

103,john,41,hyd,mark,56000

104,michel,35,chennai,hr,67000

105,clark,28,bangalore,fin,86000


ctrl+z


hive>load data local inpath 'employees.txt' overwrite into employees;





 $ cat > hivescript1.ql




$hive -S -f hivescript1.ql




7. emp salary greater than 50000

hive> select * from employees where emp_sal > 50000;


8. create view for your hive table


CREATE VIEW AGE_gt_30 AS

SELECT emp_id, emp_name, emp_age, emp_city

FROM employees

WHERE emp_age > 30;


9.execute view


SELECT * FROM AGE_gt_30;


10. drop the view


DROP VIEW IF EXISTS AGE_gt_30;


11. create index


CREATE INDEX emp_city_index

ON TABLE employees (emp_city)

AS 'COMPACT'

WITH DEFERRED REBUILD;


12. drop index

DROP INDEX IF EXISTS emp_city_index ON employees;






Sunday, 23 March 2025

matrix map reduce

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Mapper;


public class MatrixMapper extends Mapper<LongWritable, Text, Text, Text> {


    // Define matrix dimensions (m, n, p)

    private static final int m = 2; // Rows in matrix A

    private static final int n = 2; // Columns in matrix A / Rows in matrix B

    private static final int p = 2; // Columns in matrix B


    @Override

    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        // Input format: "MatrixName,i,j,Value"

        String[] tokens = value.toString().split(",");

        String matrixName = tokens[0]; // "A" or "B"

        int row = Integer.parseInt(tokens[1]); // i or k

        int col = Integer.parseInt(tokens[2]); // k or j

        double val = Double.parseDouble(tokens[3]); // A[i][k] or B[k][j]


        if (matrixName.equals("A")) {

            // Emit (i, j) as key and (A, k, A[i][k]) as value for all j in 1 to p

            for (int j = 1; j <= p; j++) {

                context.write(new Text(row + "," + j), new Text("A," + col + "," + val));

            }

        } else if (matrixName.equals("B")) {

            // Emit (i, j) as key and (B, k, B[k][j]) as value for all i in 1 to m

            for (int i = 1; i <= m; i++) {

                context.write(new Text(i + "," + col), new Text("B," + row + "," + val));

            }

        }

    }

}



----------------


import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.io.DoubleWritable;

import org.apache.hadoop.mapreduce.Reducer;


public class MatrixReducer extends Reducer<Text, Text, Text, DoubleWritable> {


    @Override

    public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {

        // Store partial products from matrix A and B

        Map<Integer, Double> aMap = new HashMap<Integer, Double>(); // Explicit type declaration

        Map<Integer, Double> bMap = new HashMap<Integer, Double>(); // Explicit type declaration


        // Iterate through all values for the given key (i, j)

        for (Text value : values) {

            String[] tokens = value.toString().split(",");

            String matrixName = tokens[0]; // "A" or "B"

            int k = Integer.parseInt(tokens[1]); // k index

            double val = Double.parseDouble(tokens[2]); // A[i][k] or B[k][j]


            if (matrixName.equals("A")) {

                aMap.put(k, val); // Store A[i][k]

            } else if (matrixName.equals("B")) {

                bMap.put(k, val); // Store B[k][j]

            }

        }


        // Compute the dot product for C[i][j]

        double result = 0.0;

        for (int k : aMap.keySet()) {

            result += aMap.get(k) * bMap.get(k); // Sum(A[i][k] * B[k][j])

        }


        // Emit the result as (i, j), C[i][j]

        context.write(key, new DoubleWritable(result));

    }

}


----------------------------


import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.Path;

import org.apache.hadoop.io.DoubleWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Job;

import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;

import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class MatrixMultiplication {


    public static void main(String[] args) throws Exception {

        // Check input arguments

        if (args.length != 2) {

            System.err.println("Usage: MatrixMultiplication <input path> <output path>");

            System.exit(-1);

        }


        // Create a Hadoop job

        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf, "Matrix Multiplication");

        job.setJarByClass(MatrixMultiplication.class);


        // Set Mapper and Reducer classes

        job.setMapperClass(MatrixMapper.class);

        job.setReducerClass(MatrixReducer.class);


        // Set output key and value types

        job.setOutputKeyClass(Text.class);

        job.setOutputValueClass(DoubleWritable.class);


        // Set input and output paths

        FileInputFormat.addInputPath(job, new Path(args[0]));

        FileOutputFormat.setOutputPath(job, new Path(args[1]));


        // Run the job and wait for completion

        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }

}



A,1,1,1.0

A,1,2,2.0

A,2,1,3.0

A,2,2,4.0


------------------------------------


B,1,1,5.0

B,1,2,6.0

B,2,1,7.0

B,2,2,8.0


----------------------------

hadoop pyspark word count example from installation

 step-by-step guide to set up Hadoop, PySpark, and implement a Word Count program using PySpark. I'll walk you through the setup process and show you how to write and run a simple Word Count program.


Step 1: Install Hadoop

  1. Download Hadoop:

    • You can download the latest stable version of Hadoop from the official Apache website: Apache Hadoop Downloads.

    • Choose a version (e.g., Hadoop 3.x.x) and download the binary release suitable for your system.

  2. Extract Hadoop:

    • After downloading Hadoop, extract the files:

    bash
    tar -xvzf hadoop-3.x.x.tar.gz
  3. Set Up Hadoop Environment Variables:

    • Edit the .bashrc or .bash_profile file to add Hadoop environment variables:

    bash
    nano ~/.bashrc

    Add the following lines to the end of the file:

    bash
    export HADOOP_HOME=/path/to/hadoop export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop export PATH=$PATH:$HADOOP_HOME/bin:$HADOOP_HOME/sbin

    Replace /path/to/hadoop with the actual Hadoop installation path.

  4. Configure Hadoop:

    • Edit the Hadoop configuration files, which are located in $HADOOP_HOME/etc/hadoop/:

      • core-site.xml: Specify HDFS URI.

        xml
        <configuration> <property> <name>fs.defaultFS</name> <value>hdfs://localhost:9000</value> </property> </configuration>
      • hdfs-site.xml: Define the replication factor and data directories.

        xml
        <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> <property> <name>dfs.namenode.name.dir</name> <value>file:/tmp/hadoop/dfs/name</value> </property> <property> <name>dfs.datanode.data.dir</name> <value>file:/tmp/hadoop/dfs/data</value> </property> </configuration>
      • Start Hadoop:

        bash
        start-dfs.sh
      • Verify Hadoop is running:

        bash
        jps

Step 2: Install Apache Spark with PySpark

  1. Download Apache Spark:

    • Go to the Apache Spark official website and download the Spark binary release (e.g., spark-3.x.x-bin-hadoop3.x.tgz): Spark Downloads.

  2. Extract Apache Spark:

    bash
    tar -xvzf spark-3.x.x-bin-hadoop3.x.tgz
  3. Set Up Spark Environment Variables:

    • Similar to Hadoop, edit .bashrc or .bash_profile and add Spark environment variables:

    bash
    nano ~/.bashrc

    Add the following lines:

    bash
    export SPARK_HOME=/path/to/spark export PATH=$PATH:$SPARK_HOME/bin

    Replace /path/to/spark with the actual path where Spark is installed.

  4. Verify Spark Installation:

    bash
    spark-shell

    If everything is set up correctly, it will open the Spark shell in Scala. To use PySpark, you can run:

    bash
    pyspark

Step 3: Set Up PySpark

  1. Install PySpark (if not already installed): You can install PySpark using pip:

    bash
    pip install pyspark
  2. Verify PySpark Installation: Run the following command to verify that PySpark is correctly installed:

    bash
    python -c "import pyspark; print(pyspark.__version__)"

Step 4: Implement Word Count Program in PySpark

Now that Hadoop and Spark are set up, let's implement a Word Count program in PySpark.

  1. Prepare Input Data:

    First, create a simple input file, input.txt, with some text data. For example:

    txt
    Hello Hadoop and Spark Hello Hadoop Spark Spark Welcome to the world of Big Data
  2. Upload the Input Data to HDFS:

    Upload the input.txt file to HDFS:

    bash
    hadoop fs -put input.txt /user/hadoop/input/
  3. Write the PySpark Word Count Program:

    Create a new Python file wordcount.py:

    python
    from pyspark import SparkContext, SparkConf # Step 1: Initialize a SparkContext conf = SparkConf().setAppName("WordCount") sc = SparkContext(conf=conf) # Step 2: Read the input text file from HDFS input_file = sc.textFile("hdfs://localhost:9000/user/hadoop/input/input.txt") # Step 3: Perform transformations to count words # 1. Split the lines into words words = input_file.flatMap(lambda line: line.split()) # 2. Map each word to a tuple of (word, 1) word_counts = words.map(lambda word: (word, 1)) # 3. Reduce by key to sum the counts for each word word_counts_reduced = word_counts.reduceByKey(lambda a, b: a + b) # Step 4: Save the output to HDFS word_counts_reduced.saveAsTextFile("hdfs://localhost:9000/user/hadoop/output/") # Step 5: Stop the SparkContext sc.stop()

Explanation of the PySpark Program:

  1. Initialize SparkContext: We set up a SparkContext to allow interaction with the Spark cluster.

  2. Read Input Data: We read the text file from HDFS into an RDD using sc.textFile().

  3. Transformations:

    • flatMap: Splits each line into words.

    • map: Transforms each word into a tuple (word, 1).

    • reduceByKey: Aggregates the counts for each word.

  4. Save Output: We save the resulting word count to HDFS using saveAsTextFile().

  5. Stop SparkContext: Finally, we stop the SparkContext.


Step 5: Run the PySpark Job

To run the wordcount.py script with Spark, use the spark-submit command:

bash
spark-submit --master yarn --deploy-mode cluster wordcount.py

Where:

  • --master yarn: Indicates that the job will run on a YARN cluster.

  • --deploy-mode cluster: Runs the job in cluster mode (driver runs on cluster node).

Alternatively, to run locally:

bash
spark-submit --master local wordcount.py

Step 6: Check the Output

Once the program runs successfully, you can check the output in HDFS:

bash
hadoop fs -ls /user/hadoop/output/

You should see output files like part-00000 in the /user/hadoop/output/ directory. To view the results:

bash
hadoop fs -cat /user/hadoop/output/part-00000

This should display the word counts, such as:

txt
Hello 2 Hadoop 2 Spark 3 and 1 Big 1 Data 1 Welcome 1 to 1 world 1 the 1 of 1

Step 7: Clean Up

Once done, you can remove the input and output files from HDFS to clean up:

bash
hadoop fs -rm -r /user/hadoop/input/ hadoop fs -rm -r /user/hadoop/output/

Summary

To summarize, the steps to set up Hadoop and PySpark and implement a Word Count program are:

  1. Set Up Hadoop: Install and configure Hadoop, and set up HDFS.

  2. Install Spark: Download, install, and configure Apache Spark.

  3. Install PySpark: Install the PySpark package using pip.

  4. Write the PySpark Word Count Program: Implement the Word Count program using PySpark.

  5. Run the Program: Use spark-submit to run the program on Hadoop/YARN or locally.

  6. Check the Output: View the output files on HDFS.

HIVE BDA LAB

 

1. Create Database in Hive

The CREATE DATABASE command in Hive is used to create a new database. By default, Hive creates databases under the /user/hive/warehouse directory on HDFS, unless you specify a different location.

Example: Creating a Simple Database

sql
-- Create a database called 'company_db' CREATE DATABASE company_db;

This creates a database named company_db.

Example: Creating a Database with a Specific Location

You can specify a custom location on HDFS for the database to store its data.

sql
-- Create a database with a custom location CREATE DATABASE company_db LOCATION '/user/hadoop/company_db_location';

This will create a database company_db and store the data at the specified HDFS path /user/hadoop/company_db_location.


2. Alter Database in Hive

You can alter a database in Hive using the ALTER DATABASE command. Some common alterations include changing the database's location or setting specific properties for the database.

Example: Altering the Location of a Database

You can change the location of a database after it has been created.

sql
-- Alter the database location ALTER DATABASE company_db SET LOCATION '/user/hadoop/new_location/';

This changes the location of the company_db database to /user/hadoop/new_location/ in HDFS.

Example: Altering the Properties of a Database

You can also modify database properties using the SET option.

sql
-- Alter database properties ALTER DATABASE company_db SET DBPROPERTIES ('owner'='John Doe', 'created_on'='2025-03-01');

This command sets custom properties for the company_db database, such as the owner and creation date.


3. Drop Database in Hive

You can drop (delete) a database using the DROP DATABASE command. This operation will remove the database and, depending on whether you use the CASCADE option, it will also delete any tables, views, and data associated with it.

Example: Dropping a Database

To drop a database without removing its tables and views:

sql
-- Drop a database without cascading DROP DATABASE company_db;

If the database has any tables or views, this command will fail.

Example: Dropping a Database with CASCADE

To drop a database and all its associated tables and views, you must use the CASCADE option:

sql
-- Drop a database and its tables/views DROP DATABASE company_db CASCADE;

This command deletes the company_db database along with any tables, views, and data inside it.


4. Show All Databases in Hive

To view all databases in Hive, you can use the SHOW DATABASES command:

sql
-- List all databases in Hive SHOW DATABASES;

This will return a list of all databases in your Hive instance.


Example Scenario: Full Script with Operations

Let's now combine all these operations into a script to demonstrate the process.

sql
-- Step 1: Create a database named 'company_db' CREATE DATABASE company_db; -- Step 2: Switch to the new database USE company_db; -- Step 3: Create a table in 'company_db' CREATE TABLE employees ( emp_id INT, emp_name STRING, emp_age INT, emp_city STRING ); -- Step 4: Alter the database properties of 'company_db' ALTER DATABASE company_db SET DBPROPERTIES ('owner'='Alice', 'created_on'='2025-03-23'); -- Step 5: Alter the database location of 'company_db' ALTER DATABASE company_db SET LOCATION '/user/hadoop/company_db_location'; -- Step 6: Show all databases to confirm 'company_db' exists SHOW DATABASES; -- Step 7: Drop the 'company_db' database along with its tables/views DROP DATABASE company_db CASCADE;

Explanation of the Script:

  1. Create Database: We created a database company_db.

  2. Use Database: We switched to company_db using the USE command.

  3. Create Table: We created a table employees in the company_db database.

  4. Alter Database Properties: We set custom properties (owner, created_on) for the database.

  5. Alter Database Location: We changed the location of the company_db database.

  6. Show Databases: We listed all databases to check if company_db exists.

  7. Drop Database: We dropped the company_db database and all its tables and views using the CASCADE option.


how to work with views, functions, and indexes in Hive, along with suitable examples for each operation.


1. Hive Views

A view in Hive is a virtual table based on the result of a query. Views do not store data physically, but they provide an abstraction layer over the data in underlying tables. You can create a view, query it like a table, and drop it when needed.

Create a View

You can create a view using the CREATE VIEW command. A view is created based on the result of a SELECT query.

Example: Creating a View to Filter Employees Over 30 Years Old

sql
-- Create a view named 'over_30_employees' which filters employees whose age is greater than 30 CREATE VIEW over_30_employees AS SELECT emp_id, emp_name, emp_age, emp_city FROM employees WHERE emp_age > 30;

In this example:

  • A view over_30_employees is created that contains the details of employees older than 30 years.

  • The view stores the query, not the data itself.

Query the View

Once the view is created, you can query it like a regular table.

sql
-- Query the view to get data SELECT * FROM over_30_employees;

Drop the View

To drop the view (delete the virtual table):

sql
-- Drop the view if it exists DROP VIEW IF EXISTS over_30_employees;

2. Hive Functions

Hive allows you to use built-in functions to perform operations on your data, such as aggregation, string operations, date functions, etc. You can also create custom UDFs (User Defined Functions) to extend the functionality of Hive.

Built-in Functions

Here are some examples of commonly used built-in functions:

  1. COUNT: Counts the number of rows.

    sql
    SELECT COUNT(*) FROM employees;
  2. CONCAT: Concatenates two or more strings.

    sql
    SELECT CONCAT(emp_name, ' lives in ', emp_city) FROM employees;
  3. YEAR: Extracts the year from a date.

    sql
    SELECT YEAR(current_date()) FROM employees;
  4. AVG: Computes the average of a numeric column.

    sql
    SELECT AVG(emp_age) FROM employees;

Creating Custom UDFs (User Defined Functions)

If you want to create custom functionality, you can write your own functions in Java and register them in Hive.

Steps to create a UDF:

  1. Write a Java UDF.

  2. Compile it into a .jar file.

  3. Register the UDF in Hive.

Here is a simple example of a custom UDF that takes a string and returns its length.

Java UDF Example (MyLengthUDF.java):

java
import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text; public class MyLengthUDF extends UDF { public int evaluate(Text str) { if (str == null) { return 0; } return str.toString().length(); } }

After compiling and creating a .jar file, you can add the UDF to Hive.

Register the UDF in Hive

sql
-- Add the JAR containing your custom UDF ADD JAR /path/to/my-udf.jar; -- Register the function CREATE FUNCTION mylength AS 'com.example.hive.udf.MyLengthUDF';

Use the Custom Function

Once registered, you can use the custom function just like built-in functions.

sql
-- Use the custom function in a query SELECT emp_name, mylength(emp_name) FROM employees;

Drop the Function

To drop a function:

sql
-- Drop the custom function DROP FUNCTION IF EXISTS mylength;

3. Hive Indexes

Indexes in Hive are used to optimize query performance by allowing faster retrieval of data from large tables. Indexes are not as commonly used in Hive as in traditional relational databases, but they can help in certain scenarios.

Create an Index

You can create an index on a table to speed up lookups on specific columns. Here’s an example of creating an index on the emp_city column in the employees table.

sql
-- Create an index on the 'emp_city' column of the 'employees' table CREATE INDEX emp_city_index ON TABLE employees (emp_city) AS 'COMPACT' WITH DEFERRED REBUILD;

In this example:

  • The index emp_city_index is created on the emp_city column.

  • The COMPACT indexing method is used, which is a basic form of indexing in Hive.

  • WITH DEFERRED REBUILD means that the index is not built immediately, and you will need to rebuild it later.

Rebuild the Index

If the index is deferred, you can rebuild it with the REBUILD command.

sql
-- Rebuild the index after it has been created ALTER INDEX emp_city_index ON employees REBUILD;

Drop an Index

To drop (delete) an index:

sql
-- Drop the index DROP INDEX IF EXISTS emp_city_index ON employees;

Full Example Scenario with Views, Functions, and Indexes

Let’s now walk through a complete scenario where we use views, functions, and indexes.

Step 1: Create a Table

sql
-- Create a table 'employees' with some sample data CREATE TABLE employees ( emp_id INT, emp_name STRING, emp_age INT, emp_city STRING ); -- Insert sample data into the table INSERT INTO employees VALUES (1, 'John Doe', 29, 'New York'), (2, 'Jane Smith', 35, 'California'), (3, 'Charlie Brown', 30, 'Texas'), (4, 'Alice Johnson', 27, 'California');

Step 2: Create a View

sql
-- Create a view to filter employees whose age is greater than 30 CREATE VIEW over_30_employees AS SELECT emp_id, emp_name, emp_age, emp_city FROM employees WHERE emp_age > 30;

Step 3: Query the View

sql
-- Query the view SELECT * FROM over_30_employees;

Step 4: Create a Custom Function (UDF)

Let’s assume you have a UDF called mylength to calculate the length of the employee's name.

sql
-- Register the UDF ADD JAR /path/to/my-udf.jar; CREATE FUNCTION mylength AS 'com.example.hive.udf.MyLengthUDF'; -- Use the UDF in a query SELECT emp_name, mylength(emp_name) FROM employees;

Step 5: Create an Index on the emp_city Column

sql
-- Create an index on the 'emp_city' column CREATE INDEX emp_city_index ON TABLE employees (emp_city) AS 'COMPACT' WITH DEFERRED REBUILD; -- Rebuild the index ALTER INDEX emp_city_index ON employees REBUILD;

Step 6: Drop the Index, View, and Function

sql
-- Drop the index DROP INDEX IF EXISTS emp_city_index ON employees; -- Drop the view DROP VIEW IF EXISTS over_30_employees; -- Drop the function DROP FUNCTION IF EXISTS mylength;

Conclusion

In this tutorial, we’ve walked through how to use views, functions (UDFs), and indexes in Hive to enhance your data management and querying capabilities. Here’s a quick summary:

  1. Views are used to simplify complex queries and act as virtual tables.

  2. Functions include both built-in functions and user-defined functions (UDFs) that you can write in Java and register in Hive.

  3. Indexes help speed up queries on large datasets by creating an index on a specific column.



Hadoop Analytics

AI & DS HUE EXPERIMENT

   STEP 1 — Create Sample Dataset (On Linux) Create emp1.csv: vi emp1.csv Paste: employee_id,name,department,salary 1,John Doe,Engineer...