Apache Pig COUNT()函數(shù)

2018-01-02 21:14 更新

Pig Latin的 COUNT() 函數(shù)用于獲取包中的元素數(shù)量。而在計算包中元組數(shù)量時, COUNT() 函數(shù)忽略(不計算)在FIRST FIELD中具有NULL值的元組。

注意

  • 要獲取全局計數(shù)值(包中的元組總數(shù)),我們需要執(zhí)行Group All操作,并使用COUNT()函數(shù)計算計數(shù)值。

  • 要獲取組的計數(shù)值(組中的元組數(shù)),我們需要使用Group By運(yùn)算符對其進(jìn)行分組,然后繼續(xù)count函數(shù)。

語法

以下給出了 COUNT() 函數(shù)的語法。

grunt> COUNT(expression)

假設(shè)在HDFS目錄 /pig_data/ 中有一個名為 student_details.txt 的文件,如下所示。

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

通過關(guān)系 student_details 將此文件加載到的Pig中,如下所示。

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);

計算元組數(shù)

我們可以使用內(nèi)置函數(shù) COUNT() (區(qū)分大小寫)來計算關(guān)系中的元組數(shù)。使用Group All運(yùn)算符將關(guān)系 student_details 分組,并將結(jié)果存儲在名為 student_group_all 的關(guān)系中,如下所示。

grunt> student_group_all = Group student_details All;

它將產(chǎn)生如下所示的關(guān)系。

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)})

現(xiàn)在讓我們計算關(guān)系中的元組/記錄的數(shù)量。

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

驗(yàn)證

使用 DUMP 運(yùn)算符驗(yàn)證關(guān)系 student_count ,如下所示。

grunt> Dump student_count;

輸出

它將產(chǎn)生以下輸出,顯示關(guān)系student_count的內(nèi)容。

8


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號