4

I am trying to figure out a way in Hive to select data from a flat source and output into an array of named struct(s). Here is a example of what I am looking for...

Sample Data:

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

Desired Output:

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"}]

I tried collect_list and collect_set but they only allow primitive data types. Any thoughts of how I might go about this in Hive?

3 Answers 3

10

I would use this jar, it is a much better implementation of collect (and takes complex datatypes).

Query:

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

Output:

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"}]
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Works as stated.
Is there a way to do this without having to declare named_struct explicitly? For example: collect(*)
@samol You can also create struct without giving names to columns, for example struct(1, 'abc') will be structure with col1 and col2 field names.
4

You can also use a workaround

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

Comments

0

You can try it using pyspark or scalaspark.. Spark sql allows both primitive and non primitive datatypes. ie., You can do collect_set( named_struct)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.