Redis set vs hash

2019-01-30 13:29发布

In many Redis tutorials (such as this one), data is stored in a set, but with multiple values combined together in a string (i.e. a user account might be stored in the set as two entries, "user:1000:username" and "user:1000:password").

However, Redis also has hashes. It seems that it would make more sense to have a "user:1000" hash, which contains a "username" entry and a "password" entry. Rather than concatenating strings to access a particular value, you just access them directly in the hash.

So why isn't it used as much? Are these just old tutorials? Or do Redis hashes have performance issues?

标签: redis
3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-30 13:53

Use case comparison:

Sets provide with a semantic interface to store data as a set in Redis server. The use cases for this kind of data would be more for an analytics purpose, for example how many people browse the product page and how many end up purchasing the product.

Hashes provide a semantic interface to store simple and complex data objects in the Redis server. For example, user profile, product catalog, and so on.

Ref: Learning Redis

查看更多
仙女界的扛把子
3楼-- · 2019-01-30 13:54

Hashes are one of the most efficient methods to store data in Redis, even going so far as to recommending them for use whenever effectively possible.

http://redis.io/topics/memory-optimization

Use hashes when possible

Small hashes are encoded in a very small space, so you should try representing your data using hashes every time it is possible. For instance if you have objects representing users in a web application, instead of using different keys for name, surname, email, password, use a single hash with all the required fields.

查看更多
我命由我不由天
4楼-- · 2019-01-30 13:56

Redis hashes are good for storing more complex data, like you suggest in your question. I use them for exactly that - to store objects with multiple attributes that need to be cached (specifically, inventory data for a particular product on an e-commerce site). Sure, I could use a concatenated string - but that adds unneeded complexity to my client code, and updating an individual field is not possible.

You may be right - the tutorials may simply be from before Hashes were introduced. They were clearly designed for storing Object representations: http://oldblog.antirez.com/post/redis-weekly-update-1.html

I suppose one concern would be the number of commands Redis must service when a new item is inserted (n number of commands, where n is the number of fields in the Hash) when compared to a simple String SET command. I haven't found this to be a problem yet on a service which hits Redis about 1 million times per day. Using the right data structure to me is more important than a negligible performance impact.

(Also, please see my comment regarding Redis Sets vs. Redis Strings - I think your question is referring to Strings but correct me if I'm wrong!)

查看更多
登录 后发表回答