【问题标题】:Hive TRANSFORM receives NULL for concatenated array valuesHive TRANSFORM 接收连接数组值的 NULL
【发布时间】:2020-12-10 05:21:34
【问题描述】:

我有一个蜂巢表,格式为:

   col1.      col2.     col3.
    a1          b1       c1
    a1          b1       c2                                  
    a1          b2       c2
    a1          b2       c3              
    a2          b3       c1
    a2          b4       c1                                  
    a2          b4       c2
    a2          b4       c3              
    .
    .

col1 中的每个值都可以在 col2 中具有多个值,并且每一对这样的 (col1, col2) 都可以具有多个 col3。

我正在运行查询[Q]

select col1, col2, collect_list(col3) from {table} group by col1, col2;

得到:

a1   b1   [c1, c2]
a1   b2   [c2, c3]
a2   b3   [c1]
a2   b4   [c1, c2, c3] 

我想使用 python UDF 进行一些转换。所以我使用 TRANSFORM 子句将所有这些列传递给 UDF:

select TRANSFORM ( * ) using 'python udf.py' FROM 
(
select col1, col2, concat_ws('\t', collect_list(col3)) from {table} group by col1, col2;
)

我正在使用 concat_ws 将数组输出转换为由分隔符连接的 collect_list 中的字符串。我得到 col1, col2 结果,但没有得到 col3 输出。

+---------+---------+
|      key|    value|
+---------+---------+
|a1       | b1      |
|         |     null|
|a1       | b2      |
|         |     null|
|a2       | b3      |
|         |     null|
|a2       | b4      |
|         |     null|
+---------+---------+

在我的 UDF 中,我只有一个打印语句,用于打印从标准输入接收到的行。

import sys
for line in sys.stdin:
    try:
        print line
    except Exception as e:
        continue

有人能帮我弄清楚为什么我的 UDF 中没有 col3 吗?

【问题讨论】:

  • 你能发布你的UDF的代码吗?没有代码,很难说出了什么问题。加上concat_ws 中的\t 不是最好的分隔符,因为制表符用于分隔列。作为替代,您可以使用逗号或分号。
  • @serge_k 我已经添加了 UDF 代码。另外,我已经用concat_ws 尝试了逗号、分号等。仍然得到相同的结果。有没有其他替代函数可以用来代替concat_ws

标签: apache-spark hive hiveql user-defined-functions hive-udf


【解决方案1】:

首先需要解析Python UDF中的行,例如,

import sys
for line in sys.stdin:
    try:
        line = line.strip('\n')
        col1, col2, col3 = line.split('\t')
        print '\t'.join([col1, col2, col3])
    except Exception as e:
        continue

那么最好在 concat_ws 中使用别的东西而不是\t

select TRANSFORM ( * )  using 'python udf.py' as (col1, col2, col3)
FROM 
(
select col1, col2, concat_ws(',', collect_list(col3)) from {table} group by col1, col2;

【讨论】:

  • 谢谢。这行得通。我之前试过 split('\t') ,不知道当时有什么问题。
  • 无论如何,在我的 UDF 中,我正在尝试汇总字典中每个唯一 col1 的所有信息并转储到 json。类似于:d = { "col1": "a1", "col2": [ "b1", "b2"], col3: ["c1", "c2", "c3"]} 所以在我的 UDF 中,我在通过 agg 创建 JSON 之后执行print json.dumps(d)。的行。但我最终得到:{"col1": "a1", "col2" : "b1", "col3": ["c1", "c2"] }{"col1": "a1", "col2" : "b2", "col3": ["c2", "c3"] }{"col1": "a2", "col2" : "b3", "col3": ["c1"] } ... 我希望group by 发送按给定列分组的 UDF 中的行,因此 col1 上的 agg 可以工作。不知道怎么回事。
猜你喜欢
  • 2020-08-12
  • 2023-03-05
  • 2013-04-20
  • 2018-06-04
  • 1970-01-01
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
相关资源
最近更新 更多