Redis 键中冒号的用途是什么

我正在学习如何使用 Redis 为我的一个项目。有一件事我还没搞清楚,那就是冒号在键名中到底是用来做什么的。

我见过这样的钥匙名称:

users:bob
color:blue
item:bag

冒号是否将键分成类别并使得找到键更快?如果是这样的话,你可以在命名键的时候使用多个冒号来把它们分成子类别吗?最后,它们是否与在 Redis 服务器中定义不同的数据库有关?

我已经阅读了大量的文档,并在谷歌上进行了大量的搜索,但奇怪的是,我找不到任何讨论这个问题的内容。

23507 次浏览

The colons have been in earlier redis versions as a concept for storing namespaced data. In early versions redis supported only strings, if you wanted to store the email and the age of 'bob' you had to store it all as a string, so colons were used:

SET user:bob:email bob@example.com
SET user:bob:age 31

They had no special handling or performance characteristics in redis, the only purpose was namespacing the data to find it again. Nowadays you can use hashes to store most of the coloned keys:

 HSET user:bob email bob@example.com
HSET user:bob age 31

You don't have to name the hash "user:bob" we could name it "bob", but namespacing it with the user-prefix we instantly know which information this hash should/could have.

Colons are a way to structure the keys. They are not interpreted by redis in any way. You can also use any other delimiter you like or none at all. I personally prefer /, which makes my keys look like file system paths. They have no influence on performance but you should not make them excessively long since redis has to keep all keys in memory.

A good key structure is important to leverage the power of the sort command, which is redis' answers to SQL's join.

GET user:bob:color   -> 'blue'
GET user:alice:color -> 'red'


SMEMBERS user:peter:friends -> alice, bob


SORT user:peter:friends BY NOSORT GET user:*:color   -> 'blue', 'red'

You can see that the key structure enables SORT to lookup the user's colors by referencing the structured keys.