Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis script to return an average

Tags:

redis

lua

I'm writing a LUA script in redis to return the result of the division of two keys (XXX_COUNT and XXX_TOTAL) already stored or 0 if any of the key doesn't exists. The code for the script is as follows:

    local count = redis.call("GET", KEYS[1]..'_COUNT')
    local total = redis.call("GET", KEYS[1]..'_TOTAL')
    if not count or not total then
        return 0
    else
        return tonumber(total)/tonumber(count)
    end

The problem is that when the script returns "tonumber(total)/tonumber(count)" it's value is always 0, already checked the keys and they have non zero values stored as strings in redis. What is wrong with this script?

Thanks in advance!

like image 373
Sergio Ayestarán Avatar asked Apr 02 '13 22:04

Sergio Ayestarán


1 Answers

I've found the solution, I needed to convert the result to string before returning it:

    local count = redis.call("GET", KEYS[1]..'_COUNT')
    local total = redis.call("GET", KEYS[1]..'_TOTAL')
    if not count or not total then
        return 0
    else
        local avg = tonumber(total)/tonumber(count)
        return tostring(avg)
    end

Hope it helps somebody!

like image 95
Sergio Ayestarán Avatar answered Sep 29 '22 08:09

Sergio Ayestarán