spacemilkman
spacemilkman

Reputation: 973

Numerical operation in Redis sort

As in the doc http://redis.io/commands/sort

SORT mylist BY weight_* 

What I would want to do is something like

SORT mylist BY (weight_* + vote_*)

Is that possible to do this just by Redis?

Upvotes: 4

Views: 106

Answers (1)

Niloct
Niloct

Reputation: 10015

You can use Lua to build each sum_* key and sort by those:

redis 127.0.0.1:6379> sadd myset 1 2 3
(integer) 0
redis 127.0.0.1:6379> mset weight_1 1 weight_2 2 weight_3 3
OK
redis 127.0.0.1:6379> mset vote_1 1 vote_2 2 vote_3 0
OK
redis 127.0.0.1:6379> eval "for i in ipairs(redis.call('smembers', KEYS[1])) do redis.call('set', 'sum_' .. i, redis.call('get','weight_' .. i) + redis.call('get', 'vote_' .. i)) end;" 1 myset
(nil)
redis 127.0.0.1:6379> sort myset by sum_*
1) "1"
2) "3"
3) "2"

Upvotes: 1

Related Questions