Search code examples
c#redis

RedisResult to List<T>


I'm calling redis function to get the elements from the redis db. However as the data is collection of JSON, I cannot convert the redisresult set, a list, or even a string[]. All the methods I'm trying to use either are not accessible in the Redis StackExchange(package in c#).

string pattern= $"Slips:{obj.Id}:{obj.Team}:{oppositeType}:*";

// Get all elements from Redis
var elEntries = await database.SortedSetRangeByRankAsync(redisKey, 0, -1);

var result = await database.ExecuteAsync("FCALL", "GetEls", 0, redisKey);

//these are some things I've tried
var elements = result.As<List<ElmentBusinessModel>>();

// consider keys as result here
foreach (var key in keys)
{
    string json = key.ToString();
    if (!string.IsNullOrEmpty(json))
    {
        var betObject = JsonSerializer.Deserialize<ElementBusinessModel>(json);
    }
}

Here is the custom function I'm getting the results from:

//the custom FCALL looks like this
FUNCTION LOAD "#!lua name=myLib 
redis.register_function('GetEls', function(keys, args) 
local pattern = args[1] 
local cursor = '0' 
local bets = {} 
    repeat 
        local result = redis.call('SCAN', cursor, 'MATCH', pattern, 'COUNT', 100) 
        cursor = result[1] 
        local keysList = result[2] 
        for _, key in ipairs(keysList) 
            do 
                local betJson = redis.call('JSON.GET', key) 
                if betJson then 
                    table.insert(els, elsJson) 
            end 
        end 
        until cursor == '0' return els 
    end)"

Solution

  • Assuming this is an array (multi-bulk) value, then something like:

    RedisResult arr = await database.ExecuteAsync("FCALL", "GetEls", 0, redisKey);
    var len = arr.Length; // non-negative for a valid array type
    // iterate the elements
    var result = new ElementBusinessModel[len]
    // or: var result = new List<ElementBusinessModel>(len);
    for (int i = 0; i < len; i++)
    {
        RedisResult el = arr[i];
        // parse
        string json = (string)el;
        var obj = JsonSerializer.Deserialize<ElementBusinessModel>(json);
        result[i] = obj;
        // or: result.Add(obj);
    }
    

    We hope to provide a much more efficient custom module/function/etc API in the next few months (that bypasses RedisResult).