Apache Pig - COUNT()


Advertisements

The COUNT() function of Pig Latin is used to get the number of elements in a bag. While counting the number of tuples in a bag, the COUNT() function ignores (will not count) the tuples having a NULL value in the FIRST FIELD.

Note

  • To get the global count value (total number of tuples in a bag), we need to perform a Group All operation, and calculate the count value using the COUNT() function.

  • To get the count value of a group (Number of tuples in a group), we need to group it using the Group By operator and proceed with the count function.

Syntax

Given below is the syntax of the COUNT() function.

grunt> COUNT(expression)

Example

Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below.

student_details.txt

001,Rajiv,Reddy,21,9848022337,Hyderabad,89
002,siddarth,Battacharya,22,9848022338,Kolkata,78 
003,Rajesh,Khanna,22,9848022339,Delhi,90 
004,Preethi,Agarwal,21,9848022330,Pune,93 
005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 
006,Archana,Mishra,23,9848022335,Chennai,87 
007,Komal,Nayak,24,9848022334,trivendram,83 
008,Bharathi,Nambiayar,24,9848022333,Chennai,72

And we have loaded this file into Pig with the relation named student_details as shown below.

grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')
   as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int);

Calculating the Number of Tuples

We can use the built-in function COUNT() (case sensitive) to calculate the number of tuples in a relation. Let us group the relation student_details using the Group All operator, and store the result in the relation named student_group_all as shown below.

grunt> student_group_all = Group student_details All;

It will produce a relation as shown below.

grunt> Dump student_group_all;
  
(all,{(8,Bharathi,Nambiayar,24,9848022333,Chennai,72),
(7,Komal,Nayak,24,9848022 334,trivendram,83),
(6,Archana,Mishra,23,9848022335,Chennai,87),
(5,Trupthi,Mohan thy,23,9848022336,Bhuwaneshwar,75),
(4,Preethi,Agarwal,21,9848022330,Pune,93),
(3 ,Rajesh,Khanna,22,9848022339,Delhi,90),
(2,siddarth,Battacharya,22,9848022338,Ko lkata,78),
(1,Rajiv,Reddy,21,9848022337,Hyderabad,89)})

Let us now calculate number of tuples/records in the relation.

grunt> student_count = foreach student_group_all  Generate COUNT(student_details.gpa);

Verification

Verify the relation student_count using the DUMP operator as shown below.

grunt> Dump student_count;

Output

It will produce the following output, displaying the contents of the relation student_count.

8
apache_pig_eval_functions.htm
Advertisements