user2694588
user2694588

Reputation: 163

Redis: Iterate/scan over all keys sorted by their value

Is it possible to iterate over all stored redis keys sorted by their value?

stored values:
  SET foo:a 1
  SET foo:b 20
  SET foo:c 5

desired output:
  SCAN 0 MATCH foo_* <some-sort-magic>
      foo:b
      foo:c
      foo:a

I cannot store foo:a, foo:b, foo:c in a sorted set, because the values change frequently.

And it would be even better if it would work for hashs too:

stored hashs:
  HSET foo:a bar 1
  HSET foo:b bar 20
  HSET foo:c bar 5

desired output:
  SCAN 0 MATCH foo_* <some-sort-magic-for-the-'bar'-field>
      foo:b
      foo:c
      foo:a

Any suggestions except getting all values and ordering in application? Thx.

Upvotes: 1

Views: 2178

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 49942

Is it possible to iterate over all stored redis keys sorted by their value?

Even if that's possible, you really don't want to do that. A full scan of the keyspace takes, storing the response takes RAM and sorting takes more time. Do you really want to keep your database occupied with that?

EDIT: If you do want to keep your database occupied with that, Redis doesn't have that out of the box. However, there are at least two additional ways to do that without having the application perform the filtering.

The first approach is to use a Lua script that performs a SCAN, gets the values and sorts them before returning the reply.

The second approach is to use Redis modules, and specifically RediSearch, to extend Redis' functionality.

I cannot store foo:a, foo:b, foo:c in a sorted set, because the values change frequently.

There's no such thing as changing too frequently - with Redis everything is done in RAM so writes are just as fast as... well, anything else.

Any suggestions except getting all values and ordering in application?

Use a Sorted Set.

Upvotes: 2

Related Questions