102

I was wondering what characters are considered valid in a Redis key. I have googled for some time and can not find any useful info.

Like in Python, valid variable name should belong to the class [a-zA-Z0-9_]. What are the requirements and conventions for Redis keys?

1 Answer 1

139

Part of this is answered here, but this isn't completely a duplicate, as you're asking about allowed characters as well as conventions.

As for valid characters in Redis keys, the manual explains this completely:

Redis keys are binary safe, this means that you can use any binary sequence as a key, from a string like "foo" to the content of a JPEG file. The empty string is also a valid key.

A few other rules about keys:

Very long keys are not a good idea, for instance a key of 1024 bytes is a bad idea not only memory-wise, but also because the lookup of the key in the dataset may require several costly key-comparisons. Even when the task at hand is to match the existence of a large value, to resort to hashing it (for example with SHA1) is a better idea, especially from the point of view of memory and bandwidth.

Very short keys are often not a good idea. There is little point in writing "u1000flw" as a key if you can instead write "user:1000:followers". The latter is more readable and the added space is minor compared to the space used by the key object itself and the value object. While short keys will obviously consume a bit less memory, your job is to find the right balance.

Try to stick with a schema. For instance "object-type:id" is a good idea, as in "user:1000". Dots or dashes are often used for multi-word fields, as in "comment:1234:reply.to" or "comment:1234:reply-to".

The maximum allowed key size is 512 MB.

5
  • 1
    So can we have space in key name here ?
    – Vipul Jain
    Apr 24, 2017 at 8:21
  • 3
    @Vipul: yes, "this means that you can use any binary sequence as a key," though on the command line you will have to put quotes around that key otherwise SET some key my value will not work, whereas SET "some key" "my value" will. May 8, 2017 at 22:20
  • 3
    Does ':' in key name create indices in Redis? Nov 29, 2017 at 6:26
  • 4
    @PankhuriAgarwal no, colon is just a handy separator. For example, some GUIs group keys in a tree-like structure by colons. And there are no indexes in a traditional sense in Redis.
    – andreycha
    Dec 29, 2017 at 15:23
  • 11
    The maximum allowed key size is 512 MB. <-- That reads like a joke after reading all about a 1024 byte long key being Bad Idea! I'm sure there's a use case for that but I couldn't imagine what that would be.
    – gillytech
    Aug 1, 2019 at 3:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.