aggregate sum on Counter type of Cassandra

我的未来我决定 提交于 2019-12-23 17:18:31

问题


I'm using Cassandra 2.2.0, and I've read using Counter type but it doesn't provide much detail.

Is there a way to aggregate on Counter type column for Cassandra, similar to the following?

SELECT sum(my_counter_column) FROM my_table ;

The above query results in this error:

InvalidRequest: code=2200 [Invalid query] message="Invalid call to
function sum, none of its type signatures match (known type
signatures: system.sum : (tinyint) -> tinyint, system.sum : (smallint)
-> smallint, system.sum : (int) -> int, system.sum : (bigint) -> bigint, 
system.sum : (float) -> float, system.sum : (double) ->
double, system.sum : (decimal) -> decimal, system.sum : (varint) ->
varint)"

I know I can fetch all data and then do aggregation in the client, but I'm just wondering if it can be done within Cassandra. Thanks a lot.


回答1:


Looks like an oversight when the system sum() function was implemented. You should probably enter a jira ticket for it here for 2.2.x and 3.x so that it can be fixed.

In the meantime you can work around the problem by defining your own user defined aggregate function (in Cassandra 2.2 and later) like this:

CREATE FUNCTION agg_counter ( state bigint, val counter )
  CALLED ON NULL INPUT
  RETURNS bigint
  LANGUAGE java
  AS '
      if (val != null)
          state = state + val;
      return state;
  ';

CREATE AGGREGATE sum_counter ( counter )
  SFUNC agg_counter
  STYPE bigint
  INITCOND 0;

Then you would use it like this:

SELECT sum_counter(countercol) FROM table WHERE partition=1;

I tried that in 3.0.0-beta2 and it works. It should also work in 2.2.

Just remember to set enable_user_defined_functions: true in cassandra.yaml before you try to create the function.



来源:https://stackoverflow.com/questions/32510572/aggregate-sum-on-counter-type-of-cassandra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!