在Apache Pig中,根据单个列选择DISTINCT行

Are*_*rel 6 group-by distinct apache-pig

假设我有一个如下表所示的表,它可能包含或不包含给定字段的重复项:

ID     URL
---    ------------------
001    http://example.com/adam
002    http://example.com/beth
002    http://example.com/beth?extra=blah
003    http://example.com/charlie
Run Code Online (Sandbox Code Playgroud)

我想写一个Pig脚本,根据单个字段的值只查找DISTINCT行.例如,过滤上面的表ID应返回如下内容:

ID     URL
---    ------------------
001    http://example.com/adam
002    http://example.com/beth
003    http://example.com/charlie
Run Code Online (Sandbox Code Playgroud)

Pig GROUP BY操作符返回一个按ID分组的元组,如果我知道如何获得每个包的第一个元组(也许是一个单独的问题),它将起作用.

Pig DISTINCT运算符适用于整行,因此在这种情况下,所有四行都将被视为唯一,这不是我想要的.

出于我的目的,我不关心002返回哪个具有ID的行.

Are*_*rel 5

我发现了一种方法,使用GROUP BYTOP运算符:

my_table = LOAD 'my_table_file' AS (A, B);

my_table_grouped = GROUP my_table BY A;

my_table_distinct = FOREACH my_table_grouped {

    -- For each group $0 refers to the group name, (A)
    -- and $1 refers to a bag of entire rows {(A, B), (A, B), ...}.
    -- Here, we take only the first (top 1) row in the bag:

    result = TOP(1, 0, $1);
    GENERATE FLATTEN(result);

}

DUMP my_table_distinct;
Run Code Online (Sandbox Code Playgroud)

这会导致每个ID列有一个不同的行:

(001,http://example.com/adam)
(002,http://example.com/beth?extra=blah)
(003,http://example.com/charlie)
Run Code Online (Sandbox Code Playgroud)

我不知道是否有更好的方法,但这对我有用.我希望这有助于其他人从猪开始.

(参考:http://pig.apache.org/docs/r0.12.1/func.html#topx)