假设我有一个如下表所示的表,该表可能包含也可能不包含给定字段的重复项:
ID URL
--- ------------------
001 http://example.com/adam
002 http://example.com/beth
002 http://example.com/beth?extra=blah
003 http://example.com/charlie
我想编写一个 Pig 脚本来仅查找不同的行,基于单个字段的值。例如,按 ID
过滤上表应返回如下内容:
ID URL
--- ------------------
001 http://example.com/adam
002 http://example.com/beth
003 http://example.com/charlie
Pig GROUP BY
运算符返回一包按 ID 分组的元组,如果我知道如何获取每个包的第一个元组(可能是一个单独的问题),那么这将起作用。
Pig DISTINCT
运算符适用于整行,因此在这种情况下,所有四行都将被视为唯一,这不是我想要的。
就我的目的而言,我不关心返回 ID 为 002
的哪些行。
最佳答案
我找到了一种方法来做到这一点,即使用 GROUP BY
和 TOP
运算符:
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;
这会导致每个 ID 列有一个不同的行:
(001,http://example.com/adam)
(002,http://example.com/beth?extra=blah)
(003,http://example.com/charlie)
我不知道是否有更好的方法,但这对我有用。我希望这可以帮助其他开始使用 Pig 的人。
关于group-by - 在 Apache Pig 中,根据单列选择不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23900796/