Redis key naming conventions?
We use a colon (:) as namespace separator and a hash (#) for id-parts of keys, e.g.:
logistics:building#23
A convention seems to be colon (:) but I'm a web developer so I personally prefer slash (/) for the separator. Slash is already so important separator within URLs which are meant to be Uniform Resource Locators so kind of keys for resources. Why to take a different approach with colon (:)? Does it help anything?
Consider this example:
We have an RESTful API for toy objects. There is a one:
http://example.com/api/toy/234
Where we have it stored? We use Redis and slashes so the key is obvious:
toy/234
This is the unique key for the toy. The key can now be used also on client side:
{
key: "toy/234",
color: "red",
url: function () {
return API_BASE_URL + this.key;
}
}
An user requests an object with key toy/666
. How to get it from Redis? A Node.js related example:
redis.get(key, function reply_callback(error, toystring) {
var toy = JSON.parse(toystring);
...
}
No need to convert slashes to colons and vice versa. Convenient, don't you think?
Warning: always ensure that user is able to access only things you intended. The raw URL-to-key approach above is able to fetch user/1/password
as well, as noted by commentators. This should not be a problem if you use Redis as a public read-only cache.
What are the normal naming convention for keys in redis? I've seen values separated by : but I'm not sure what the normal convention is, or why.
Yes, colon sign :
is a convention when naming keys. In this tutorial on redis website is stated: Try to stick with a schema. For instance "object-type:id:field" can be
a nice idea, like in "user:1000:password". I like to use dots for
multi-words fields, like in "comment:1234:reply.to".
Are you able to query for just the beginning of the key to return all users?
If you mean something like directly querying for all keys which starts with user:
there is a keys command for that. This command should be however used only for debugging purpose since it's O(N) because it's searching through all keys stored in database.
More appropriate solution for this problem is to create dedicated key, let's name it users
, which will store all the users keys, for example, in list or set data structure.