V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
linuxchild
V2EX  ›  Hadoop

spark 计算 array 非空的数量

  •  
  •   linuxchild · 2017-10-16 11:43:31 +08:00 · 4792 次点击
    这是一个创建于 2355 天前的主题,其中的信息可能已经有所发展或是发生改变。

    格式如下

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

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

    小白提问,勿喷。

    感谢各位

    9 条回复    2017-10-16 16:05:46 +08:00
    liprais
        1
    liprais  
       2017-10-16 11:46:11 +08:00 via iPhone
    array 长度大于零呗
    linuxchild
        2
    linuxchild  
    OP
       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
        3
    linuxchild  
    OP
       2017-10-16 12:08:47 +08:00
    @liprais 哎,搞错了。

    提示了满屏的警告后,然后出来了一个数……
    noNOno
        4
    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
        5
    linuxchild  
    OP
       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
        6
    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
        7
    linuxchild  
    OP
       2017-10-16 15:41:32 +08:00
    @noNOno 加上 end 可以了。

    多问一句,array 的长度用什么函数? 在 sql 中写 email.length() email.size()都会提示 Undefined function 错误
    noNOno
        8
    noNOno  
       2017-10-16 15:51:09 +08:00
    @linuxchild size(email)
    linuxchild
        9
    linuxchild  
    OP
       2017-10-16 16:05:46 +08:00
    @noNOno 谢谢耐心回复,感谢感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3127 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:58 · PVG 20:58 · LAX 05:58 · JFK 08:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.