spark 计算 array 非空的数量

2017-10-16 11:43:31 +08:00
 linuxchild

格式如下

|-- email: array (nullable = true) | |-- element: string (containsNull = true)

想计算 dataframe 中 email 非空的数量,该如何计算

小白提问,勿喷。

感谢各位

4809 次点击
所在节点    Hadoop
9 条回复
liprais
2017-10-16 11:46:11 +08:00
array 长度大于零呗
linuxchild
2017-10-16 12:04:36 +08:00
@liprais

查询语句是下面这种,其中 tb_name 是 dataframe 创建出来的 TempView:

scala> var test=spark.sql("select count(email) from tb_name where IsNotNull(email[0])")

scala> test.show()

但是这样会提示
Can not initialize counter due to context is not a instance of TaskInputOutputContext, but is org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl

最终计算结果不正确,请问您知道我是哪里搞错了么
linuxchild
2017-10-16 12:08:47 +08:00
@liprais 哎,搞错了。

提示了满屏的警告后,然后出来了一个数……
noNOno
2017-10-16 12:41:34 +08:00
spark.sql("select count(case when isnotnull(email[0]) then 1 else null),count(1) from tb_name")
这样调试一下看看
linuxchild
2017-10-16 14:41:12 +08:00
@noNOno 这样好像语法有问题,提示

org.apache.spark.sql.catalyst.parser.ParseException:
mismatched input 'when' expecting {')', ',', '.', '[', 'OR', 'AND', 'IN', NOT, 'BETWEEN', 'LIKE', RLIKE, 'IS', EQ, '<=>', '<>', '!=', '<', LTE, '>', GTE, '+', '-', '*', '/', '%', 'DIV', '&', '|', '^'}(line 1, pos 18)
noNOno
2017-10-16 14:50:52 +08:00
@linuxchild 不好意思,case when 少写了个 End.
然后我想说的是,你的 IsNotNull(email[0])放在了 where 条件中 /作为过滤条件,查询的时候实际上会把 array 解析为多行.有可能的情况是 email[0]为 null,但是 email 不是 null.
建议用 array 长度来判断是否是 null
linuxchild
2017-10-16 15:41:32 +08:00
@noNOno 加上 end 可以了。

多问一句,array 的长度用什么函数? 在 sql 中写 email.length() email.size()都会提示 Undefined function 错误
noNOno
2017-10-16 15:51:09 +08:00
@linuxchild size(email)
linuxchild
2017-10-16 16:05:46 +08:00
@noNOno 谢谢耐心回复,感谢感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/397966

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX