Hive将数据选择为结构数组

时间:2015-09-03 21:07:00

标签: sql hadoop hive apache-pig hiveql

我试图在Hive中找到一种方法,从平面源中选择数据并输出到一个名为struct的数组中。这是我正在寻找的一个例子......

示例数据:

house_id,first_name,last_name
1,bob,jones
1,jenny,jones
2,sally,johnson
3,john,smith
3,barb,smith

期望的输出:

1   [{"first_name":"bob","last_name":"jones"},{"first_name":"jenny","last_name":"jones"}]
2   [{"first_name":"sally","last_name":"johnson"}]
3   [{"first_name":"john","last_name":"smith"},{"first_name":"barb","last_name":"smith"}]

我尝试了collect_list和collect_set,但它们只允许原始数据类型。有关如何在Hive中解决这个问题的想法吗?

3 个答案:

答案 0 :(得分:7)

我会使用这个jar,它是collect的一个更好的实现(并采用复杂的数据类型)。

<强>查询

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

select house_id
  , collect(named_struct("first_name", first_name, "last_name", last_name))
from db.table
group by house_id

<强>输出

1   [{"first_name":"bob","last_name":"jones"}, {"first_name":"jenny","last_name":"jones"}]
2   [{"first_name":"sally","last_name":"johnson"}]
3   [{"first_name":"john","last_name":"smith"},{"first_name":"barb","last_name":"smith"}]

答案 1 :(得分:2)

您还可以使用解决方法

select collect_list(full_name) full_name_list from (
    select 
        concat_ws(',', 
            concat("first_name:",first_name), 
            concat("last_name:",last_name)
            ) full_name, 
        house_id
    from house) a 
group by house_id

答案 2 :(得分:0)

您可以使用pyspark或scalaspark进行尝试。Spark sql允许原始和非原始数据类型。 即,您可以执行collect_set(named_struct)