In Azure Redis Enterprise with TimeSeries module enabled I have the following time series with 4 values of 1 at the key "key1":
$ TS.RANGE key1 - +
1) 1) (integer) 1693381431951
2) 1
2) 1) (integer) 1693381435201
2) 1
3) 1) (integer) 1693381436720
2) 1
4) 1) (integer) 1693381438037
2) 1
I am able to retrieve the same results by a Lua script:
$ EVAL "return redis.call('TS.RANGE', KEYS[1], '-', '+')" 1 key1
1) 1) (integer) 1693381431951
2) 1
2) 1) (integer) 1693381435201
2) 1
3) 1) (integer) 1693381436720
2) 1
4) 1) (integer) 1693381438037
2) 1
My question is how to sum up the values (and to get a 4 as result in the shown case)?
I am trying the following Lua code:
$ EVAL "local sum = 0; for stamp, val in redis.call('TS.RANGE', KEYS[1], '-', '+') do sum = sum + val end; return sum" 1 key1
(error) ERR Error running script (call to f_28243bc2b451f1770c76c1d7fcce23e7285f3baa): @user_script:1: user_script:1: attempt to call a table value
Doesn’t TS.RANGE return pairs of timestamp and numeric values?
My background is that I am calling ScriptEvaluateAsync()
in my C# application and would like to sum up all values in a time series, when given a key.
2
Answers
By looking at the
cjson.encode(tsrange)
I have come up with the following solution, which I also would like to share:And then I call it in my C# app as:
this can get a bit messy and the Redis Lua debugger can help (https://redis.io/docs/interact/programmability/lua-debugging/).
Here’s a solution that will do what you need but the Lua could possibly be optimized – I’m not a Lua expert 🙂
This unpacks the
TS.RANGE
response and sums the values. Let’s set up some data to use it:and check what we have:
Now let’s store the script in the redis server (I’ve put the script in a file called
sumts.lua
:We get the SHA for the script back and can use that to call it:
we get the integer response 4, the sum of the values in the time series.
Here’s an example of how to run through this script in the Lua debugger and see local variables:
then…
You can keep using
n
to step through the loop.Hope this helps.