select count distinct using pig latin
Asked Answered
P

3

17

I need help with this pig script. I am just getting a single record. I am selecting 2 columns and doing a count(distinct) on another while also using a where like clause to find a particular description (desc).

Here's my sql with pig I am trying to code.

 /*
    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;
Prosaic answered 12/2, 2012 at 7:55 Comment(0)
H
34

You could GROUP on each domain and then count the number of distinct elements in each group with a nested FOREACH syntax:

D = group C by domain;
E = foreach D { 
    unique_segments = DISTINCT C.segment;
    generate group, COUNT(unique_segments) as segment_cnt;
};
Homogenous answered 12/2, 2012 at 19:12 Comment(1)
I think to be perfect it should be unique_segments = DISTINCT C.segment;Profant
A
3

You can better define this as a macro:

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

Usage:

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

Y = DISTINCT_COUNT(X, x);

If you need to use it in a FOREACH instead then the easiest way is something like:

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

Tested on Pig 12.

Avertin answered 9/2, 2015 at 10:30 Comment(0)
N
1

If you don't want to count on any group, you use this:

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

This will just give you a number.

Np answered 12/1, 2018 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.