如何在pig或hive中使用array_agg()聚合函数

时间:2015-09-18 14:38:12

标签: python hive apache-pig aggregate-functions array-agg

我有以下数据:

================================================================
session_id                       screen_name  screen_launch_time
================================================================
990004916946605-1404157897784    screen1      1404157898275
990004916946605-1404157897784    screen2      1404157898337
990004947764274-1435162269418    screen1      1435162274044
990004947764274-1435162269418    screen3      1435162274081

我想使用array_agg函数以下列格式获取数据:

=========================================================
session_id                      screen_flow         count
=========================================================
990004916946605-1404157897784   screen1->screen2    1
990004947764274-1435162269418   screen1->screen3    1

是否有人尝试编写UDAFpython脚本来实现array_agg函数中使用的逻辑?

请分享您的想法。

2 个答案:

答案 0 :(得分:3)

只需按session_id,concat screen_name进行分组,并计算每组的记录数。如果您不想构建brickhouse jar,则可以使用collect_list()代替collect()(但我不推荐)。

<强>查询

add jar /path/to/jars/brickhouse-0.7.1.jar;
create temporary function collect as "brickhouse.udf.collect.CollectUDAF";

select session_id, screen_flow
  , count(*) count
from (
  select session_id
    , concat_ws('->', collect(screen_name)) screen_flow
  from db.table
  group by session_id ) x
group by session_id, screen_flow

<强>输出

990004916946605-1404157897784   screen1->screen2    1
990004947764274-1435162269418   screen1->screen3    1

答案 1 :(得分:1)

输入: -

990004916946605-1404157897784,screen1,1404157898275
990004916946605-1404157897784,screen2,1404157898337
990004947764274-1435162269418,screen1,1435162274044
990004947764274-1435162269418,screen3,1435162274081

以下是Pig Style的答案..

records = LOAD '/user/user/inputfiles/session_id.txt' USING PigStorage(',') AS (session_id:chararray,screen_name:chararray,screnn_launch_time:chararray);

rec_grped = GROUP records BY session_id;

rec_each =  FOREACH rec_grped 
                     {
                       rec_inner_each = FOREACH records GENERATE screen_name;

                       GENERATE group as session_id, REPLACE(BagToString(rec_inner_each),'_','-->') as screen_flow, 1 as cnt;
};

dump rec_each; 

输出: -

990004916946605-1404157897784   screen1-->screen2    1
990004947764274-1435162269418   screen1-->screen3    1