12

I'm trying to use a pattern to retrieve all keys matching a pattern by Stackexchange.Redis.

Code

KEYS *o*
Richard
  • 6,812
  • 5
  • 45
  • 60
Amir Movahedi
  • 1,802
  • 3
  • 29
  • 52

1 Answers1

10

On the project homepage is linked Where are KEYS, SCAN, FLUSHDB etc? which gives full details on how to access this, and why it isn't on IDatabase. I should point out that you should avoid KEYS on a production server. The library will automatically try to use SCAN instead if it is available - which is less harmful but should still be treated with some caution. It would be preferable to explicitly store related keys in a set or hash.

BenV
  • 12,052
  • 13
  • 64
  • 92
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    @MarkGravell, would you please clarify why the server.Keys(pattern: "*foo*") shouldn't be used if we are using 2.8+ instance of Redis? I read the link/page you refer to but it seems to contradict the advice given at https://redis.io/commands/scan where it says: "Since these commands allow for incremental iteration, returning only a small number of elements per call, they can be used in production without the downside of commands like KEYS". – Jeff Zickgraf Aug 11 '17 at 20:36
  • @Jeff I said it should still be "treated with some caution" - not that it shouldn't be used. Frankly, redis is just *slow* for this scenario (on a busy server) - it is O(N) for N=number of keys on server. I would advocate using a *set* that contains the active keys for your scenario, so you can use SMEMBERS / SSCAN – Marc Gravell Aug 11 '17 at 21:32
  • @MarkGravel - Thank you. – Jeff Zickgraf Aug 14 '17 at 23:06
  • @MarcGravell If you do that, how do you deal with items that expire? If I store an item with a TTL of N minutes, after that time the key name will still be in my list but my saved item will be gone and my list of keys will be stale. – howcheng Jan 16 '19 at 00:04
  • @howcheng indeed; if you go with key sets, your code would need to deal with missing records appropriately; you could also use the `SORT` instruction, which allows the `GET` modifier to be used to perform a "gather" operation (essentially doing an "inner join", in SQL terms) – Marc Gravell Jan 16 '19 at 09:16