使用猪拉丁选择计数明显

时间:2012-02-12 07:55:38

标签: hadoop apache-pig

我需要这个猪脚本的帮助。我刚收到一条记录。我正在选择2列并在另一列上进行计数(不同),同时还使用where where子句来查找特定描述(desc)。

这是我正在尝试编码的猪的sql。

 /*
    For example in sql:
    select domain, count(distinct(segment)) as segment_cnt
    from table
    where desc='ABC123'
    group by domain
    order by segment_count desc;
    */

    A = LOAD 'myoutputfile' USING PigStorage('\u0005')
            AS (
                domain:chararray,
                segment:chararray,
                desc:chararray
                );
B = filter A by (desc=='ABC123');
C = foreach B generate domain, segment;
D = DISTINCT C;
E = group D all;
F = foreach E generate group, COUNT(D) as segment_cnt;
G = order F by segment_cnt DESC;

3 个答案:

答案 0 :(得分:33)

您可以在每个域上进行GROUP,然后使用nested FOREACH语法计算每个组中不同元素的数量:

D = group C by domain;
E = foreach D { 
    unique_segments = DISTINCT C.segment;
    generate group, COUNT(unique_segments) as segment_cnt;
};

答案 1 :(得分:1)

您可以更好地将其定义为宏:

DEFINE DISTINCT_COUNT(A, c) RETURNS dist {
  temp = FOREACH $A GENERATE $c;                                                                                                                                                      
  dist = DISTINCT temp;                                                                                                                                                               
  groupAll = GROUP dist ALL;                                                                                                                                                          
  $dist = FOREACH groupAll GENERATE COUNT(dist);                                                                                                                                      
}

用法:

X = LOAD 'data' AS (x: int);

Y = DISTINCT_COUNT(X, x);

如果您需要在FOREACH中使用它,那么最简单的方法就是:

...GENERATE COUNT(Distinct(x))...

在猪12上测试。

答案 2 :(得分:0)

如果您不想指望任何群体,请使用此:

G = FOREACH (GROUP A ALL){
unique = DISTINCT A.field;
GENERATE COUNT(unique) AS ct;
};

这只会给你一个号码。