【问题标题】:Handling null values in Map keys处理 Map 键中的空值
【发布时间】:2019-02-28 03:08:50
【问题描述】:

我正在使用 cassandra 3.10,为了在非主分区上使用 Group by 函数,我指的是:http://www.batey.info/cassandra-aggregates-min-max-avg-group.html,它使用映射键来做同样的事情。当我执行select group_and_total(name,count) from school; 并收到错误ServerError: java.lang.NullPointerException: Map keys cannot be null。 问题是 name 列中有一些空值,有没有办法通过修改函数并获得所需的结果,而不是删除其中包含空值的行。

表的架构是

Table school{
name text,
count int,
roll_no text,
...
primary key(roll_no)
}

我用于 Group by 的功能是:

CREATE FUNCTION state_group_and_total( state map<text, int>, type text, amount int )
CALLED ON NULL INPUT
RETURNS map<text, int>
LANGUAGE java AS '
Integer count = (Integer) state.get(type);  if (count == null) count = amount; else count = count + amount; state.put(type, count); return state; ' ;


CREATE OR REPLACE AGGREGATE group_and_total(text, int) 
SFUNC state_group_and_total 
STYPE map<text, int> 
INITCOND {};

【问题讨论】:

    标签: cassandra


    【解决方案1】:

    您提到的架构

    CREATE TABLE temp.school (
        roll_no text PRIMARY KEY,
        count int,
        name text
    )
    

    表格输入示例

     roll_no | count | name
    ---------+-------+------
           6 |     1 |    b
           7 |     1 | null
           4 |     1 |    b
           3 |     1 |    a
           5 |     1 |    b
           2 |     1 |    a
           1 |     1 |    a
    
    (7 rows)
    

    注意:名称列中只有一个空值。

    修改函数定义

    CREATE FUNCTION temp.state_group_and_total(state map<text, int>, type text, amount int)
        RETURNS NULL ON NULL INPUT
        RETURNS map<text, int>
        LANGUAGE java
        AS $$Integer count = (Integer) state.get(type);if (count == null) count = amount;else count = count + amount;state.put(type, count); return state;$$;
    

    注意:删除CALLED ON NULL INPUT并添加RETURNS NULL ON NULL INPUT

    聚合定义:

    CREATE AGGREGATE temp.group_and_total(text, int)
        SFUNC state_group_and_total
        STYPE map<text, int>
        INITCOND {};
    

    查询输出:

    cassandra@cqlsh:temp> select group_and_total(name,count) from school;
    
     temp.group_and_total(name, count)
    -----------------------------------
                      {'a': 3, 'b': 3}
    
    (1 rows)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 2017-06-05
      • 2014-02-09
      • 2012-05-23
      相关资源
      最近更新 更多