Search code examples
pythonredisredis-py

How can I sort a hash with sort?


I am trying to know how I can sort a hash with redis-py.

I have the following code:

redis_db.hmset('data:1',{'n':1, 'user': 'a'})
redis_db.hmset('data:2',{'n':4, 'user': 'b'})
redis_db.hmset('data:3',{'n':5, 'user': 'c'})
redis_db.hmset('data:4',{'n':2, 'user': 'd'})
redis_db.hmset('data:5',{'n':3, 'user': 'e'})
redis_db.sort('data*', by='data:*->n', get=['data:*->n'])

But I only can I get an empty array, why? how can I do it to get a sorted list of n values with n and user?

Thanks.


Solution

  • You got an empty array, because the key data* doesn't exist.

    You can only sort a LIST, SET, or SORTED SET. So first of all, you need to put data index, e.g. 1, 2, 3, 4, 5, into a LIST, SET or SORTED SET. And then sort it by the value in HASH.

    LPUSH indexes 1 2 3 4 5
    
    SORT indexes by data:*->n get data:*->user