DEV Community

Alex Friedman
Alex Friedman

Posted on

Sorting by external keys in Redis with Python

Sometimes you want to sort elements using external keys as weights to compare instead of comparing the actual elements in the list, set or sorted set. Let's say the list indices contains the elements key0, key1, and key3 representing unique IDs of objects stored in as key0, key1, and key3. When these objects have associated weights stored in their hash, SORT can be instructed to use these weights to sort indices.

>>> from random import randint
>>> import redis
>>> r = redis.Redis(host='localhost', port=6379)

>>> for i in range(3):
...     key = f'key{i}'
...     r.hset(key, 'weight', randint(0, 100))
...     r.sadd('indices', key)

>>> # Show the weights of each Hash
>>> [(f'key{i}', r.hget(f'key{i}', 'weight')) for i in range(3)]
[('key0', b'91'), ('key1', b'40'), ('key2', b'63')]

>>> r.sort('indices', by='*->weight')
[b'key1', b'key2', b'key0']
Enter fullscreen mode Exit fullscreen mode

Top comments (0)