roger
roger

Reputation: 9893

How can I get group data and collect the result into a map in Hive?

I have a table like this:

id |    job     | school  |
1  | programmer | school1 |
2  | programmer | school1 |
3  | programmer | school2 |
4  |     pm     | school3 |
5  |     pm     | school2 |
6  |     pm     | school3 |

I want to do the following:

  1. Group by job
  2. Get school list and count, like this[(school1, 2), (school2, 1)]
  3. School list order by count, so can NOT be [(school1, 1), (school1, 2)]

The result of the example is:

programmer  |  [(school1, 2), (school2, 1)]
    pm      |  [(school3, 2), (school2, 1)]

Upvotes: 1

Views: 3952

Answers (2)

o-90
o-90

Reputation: 17585

Just add the Brickhouse jar and create a collect() function

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

select job
  , collect(school, c) school_count_map
from (
  select *
  from (
    select job, school
      , count( * ) c
    from table
    group by job, school ) x
  order by job, c desc) y
group by job

Upvotes: 1

Partha Kaushik
Partha Kaushik

Reputation: 690

We can't have a Map inside a Collection (collect_set) in hive (coz only primitive datatypes are allowed inside a collect_set).

These 2 queries will give what you look for (Both are same except that one involves map other doesn't)

CREATE EXTERNAL TABLE job_test(
  id string,
  job string,
  school string )
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION  '/user/test/job.txt';

SELECT b.job, collect_set(concat_ws(':',map_keys(b.school_map),map_values(b.school_map))) as school_cnt
FROM
(
    SELECT a.job, map(a.school,a.cnt) as school_map
    FROM
    ( 
         SELECT job,
                school, 
                cast(count(1) as string) as cnt
         FROM job_test
         GROUP BY 
                job,
                school
    )a
)b
GROUP BY b.job;

SELECT a.job, collect_set(concat_ws(':',a.school,a.cnt)) as school_cnt
FROM
(
     SELECT job,
            school,
            cast(count(1) as string) as cnt
     FROM job_test
     GROUP BY 
            job,
            school
)a
GROUP BY a.job;

Hope this helps :)

Upvotes: 1

Related Questions