DEV Community

Alex Friedman
Alex Friedman

Posted on

1

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)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay