Reputation: 43
Is it possible to sort number of lists by "column" in Redis like this:
mylist 3 5 6
mylist2 1 6 8
mylist3 4 9 3
(sort by first column)
mylist2 1 6 8
mylist 3 5 6
mylist3 4 9 3
Upvotes: 1
Views: 52
Reputation: 49942
Yes, but you'll have to prepare the data for it. One way for doing it is using a Sorted Set in which you'll keep the lists' key names as members and the scores as the first member ("column") of these. Note that you'll have to update this Sorted Set whenever you make changes to the relevant lists.
In your example, the Sorted Set should be created with:
ZADD lists_index 3 mylist 1 mylist2 4 mylist3
To get the sorted list of lists, do ZRANGEBYSCORE lists_index -inf +inf
.
Update: following the OP's comment, Lua would be a way of tackling this, like so:
local t = {}
for _, k in pairs(KEYS) do
local s = redis.call('LINDEX', k, ARGV[1])
t[#t+1] = { s, k }
end
table.sort(t, function (a, b)
return (a[1] < b[1])
end)
local r = {}
for i, v in pairs(t) do
r[#r+1] = v[2]
end
return r
And run it this way:
$ redis-cli --eval sort_by_column.lua mylist mylist2 mylist3 , 0
1) "mylist2"
2) "mylist"
3) "mylist3"
Note, however, that using this approach will require more resources whenever you invoke this sort operation (as opposed the the Sorted Set that is maintained continuously).
Upvotes: 3