Apache Pig COUNT_STAR()函數(shù)

2018-01-02 21:20 更新

Pig Latin的 COUNT_STAR() 函數(shù)與 COUNT() 函數(shù)類似。它用于獲取包中的元素?cái)?shù)量。在計(jì)數(shù)元素時(shí), COUNT_STAR() 函數(shù)包含NULL值。

注意

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

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

語法

下面給出了 COUNT_STAR() 函數(shù)的語法。

grunt> COUNT_STAR(expression)

假設(shè)在HDFS目錄 /pig_data/ 中有一個(gè)名為 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);

計(jì)算元組數(shù)

我們可以使用內(nèi)置函數(shù) COUNT_STAR() 來計(jì)算關(guān)系中的元組數(shù)。讓我們使用Group All運(yùn)算符將關(guān)系 student_details 分組,并將結(jié)果存儲(chǔ)在名為 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)在讓我們計(jì)算關(guān)系中的元組/記錄的數(shù)量。

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

9

因?yàn)槲覀兪褂昧撕瘮?shù) COUNT_STAR() ,它包含了null元組并返回9。

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)