Apache Pig - COUNT_STAR()



The COUNT_STAR() function of Pig Latin is similar to the COUNT() function. It is used to get the number of elements in a bag. While counting the elements, the COUNT_STAR() function includes the NULL values.

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_star value using the COUNT_STAR() 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_star function.

Syntax

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

grunt> COUNT_STAR(expression)

Example

Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below. This file contains an empty record.

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 name 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_STAR() 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 the number of tuples/records in the relation.

grunt> student_count = foreach student_group_all  Generate COUNT_STAR(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.

9

Since we have used the function COUNT_STAR(), it included the null tuple and returned 9.

apache_pig_eval_functions.htm
Advertisements