with the worst case. When we say that something takes O(N), we might actually find it right away or it might be the last possible element. Pseudo Multi Key Queries A common situation you'll run into is wanting to query the same value by different keys. For example, you might want to get a user by email (for when they first log in) and also by id (after they've logged in). One horrible solution is to duplicate your user object into two string values: set users:
[email protected] "{id: 9001, email: '
[email protected]', ...}" set users:9001 "{id: 9001, email: '
[email protected]', ...}" This is bad because it's a nightmare to manage and it takes twice the amount of memory. It would be nice if Redis let you link one key to another, but it doesn't (and it probably never will). A major driver in Redis' development is to keep the code and API clean and simple. The internal implementation of linking keys (there's a lot we can do with keys that we haven't talked about yet) isn't worth it when you consider that Redis already provides a solution: hashes. Using a hash, we can remove the need for duplication: set users:9001 "{id: 9001, email:
[email protected], ...}" hset users:lookup:email
[email protected] 9001 What we are doing is using the field as a pseudo secondary index and referencing the single user object. To get a user by id, we issue a normal get: get users:9001 To get a user by email, we issue an hget followed by a get (in Ruby): id = redis.hget('users:lookup:email', '
[email protected]') user = redis.get("users:#{id}") This is something that you'll likely end up doing often. To me, this is where hashes really shine, but it isn't an obvious use-case until you see it. 15