I am building a wallet app and I am using redis for caching the current wallet balance of a user. I was asked to retrieve the sum of the entire balance of all users using the application. I have been looking for a way to query redis for this data since it's already cached there.
The keys I used to save them are user_id-current-balance. Is there a way I can get all the keys ending with -current-balance and then retrieve all the data they hold? Is there a better way to do this?
You can get all matching keys, then sum the values of the keys in a loop. Use one of the following to obtain the keys:
KEYS pattern: O(N) with N being the number of keys in the database
This is generally not a performant solution (but if your db is very small, you can test the query cost).
SMEMBERS key: O(N) where N is the set cardinality
Using this technique, you'd create a set at key and then add each key holding a user balance (e.g. user_id_1-current-balance, user_id_2-current-balance, etc.).