问题
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