apache pig无法进行分组和计数

时间:2016-01-19 17:25:27

标签: hadoop apache-pig

我是Pig脚本的新手。请帮我解决这个问题。 我不知道我哪里出错了。

我的数据

(catA,myid_1,2014,store1,appl)
(catA,myid_2,2014,store1,milk)
(catA,myid_3,2014,store1,appl)
(catA,myid_4,2014,store1,milk)
(catA,myid_5,2015,store1,milk)
(catB,myid_6,2014,store2,milk)
(catB,myid_7,2014,store2,appl)

以下是预期的结果

(catA,2014,milk,2)
(catA,2014,apple,2)
(catA,2015,milk,1)
(catB,2014,milk,1)
(catB,2014,apple,1)

需要根据类别,年份计算食品数量。 下面是我的猪脚本

list = LOAD 'shop' USING PigStorage(',') AS (category:chararray,id:chararray,mdate:chararray,my_store:chararray,item:chararray);
list_of = FOREACH list GENERATE category,SUBSTRING(mdate,0,4) as my_date,my_store,item;
StoreG = GROUP list_of BY (category,my_date,my_store);
result = FOREACH StoreG
{
food_list = FOREACH list_of GENERATE item;
food_count = DISTINCT food_list;
GENERATE FLATTEN(group) AS (category,my_date,my_store),COUNT(food_count);
 }
DUMP result;

上面脚本的输出在

之下
(catA,2014,store1,2)
(catA,2015,store1,1)
(catB,2014,store2,2)

有谁可以让我知道我的脚本在哪里错了 感谢

2 个答案:

答案 0 :(得分:0)

StoreG = GROUP list_of BY (category,my_date,my_store);

应该是

StoreG = GROUP list_of BY (category,my_date,item);

因为您的预期结果是按商品分组而不是商店。

答案 1 :(得分:0)

一种方法。没有最优雅但又有效的例子:

list = LOAD 'shop' USING PigStorage(',') AS (category:chararray,id:chararray,mdate:chararray,my_store:chararray,item:chararray);

list_of = FOREACH list GENERATE category,SUBSTRING(mdate,0,4) AS my_date,my_store,item;

StoreG = GROUP list_of BY (category,my_date,my_store,item);

result = FOREACH StoreG GENERATE 
      group.category AS category,
      group.my_date AS my_date,
      group.my_store AS mys_store,
      group.item AS item, 
      COUNT(list_of.item) AS nb_items;

DUMP result;

当我们向GROUP BY语句添加别名 item 时,基本上与查找不同的项目相同,然后对它们进行计数(正如您在括号中所做的那样)。

如果您仍想使用代码,只需在下面的代码中添加food_list.item关系:

result = FOREACH StoreG
{
food_list = FOREACH list_of GENERATE item;
food_count = DISTINCT food_list;
GENERATE FLATTEN(group) AS (category,my_date,my_store),food_list.item,COUNT(food_count);
 }