python - redis - 使用哈希

标签 python django nosql memcached redis

我正在使用 Redis 为我的 Web 应用程序实现社交流和通知系统。我是 Redis 的新手,我对哈希及其效率有一些疑问。

我读过这个很棒的 Instagram post 我计划实现他们的类似解决方案以实现最少的存储。

正如他们博客中提到的,他们确实喜欢这样

To take advantage of the hash type, we bucket all our Media IDs into buckets of 1000 (we just take the ID, divide by 1000 and discard the remainder). That determines which key we fall into; next, within the hash that lives at that key, the Media ID is the lookup key within the hash, and the user ID is the value. An example, given a Media ID of 1155315, which means it falls into bucket 1155 (1155315 / 1000 = 1155):

HSET "mediabucket:1155" "1155315" "939"
HGET "mediabucket:1155" "1155315"
> "939"

因此,他们没有使用 1000 个单独的键,而是将其存储在一个具有数千个查找键的散列中。 我的疑问是为什么我们不能将查找键值增加到更大。

例如: 1155315 的媒体 ID 除以 10000 将落入 mediabucket:115 甚至更大。

他们为什么要使用一个包含 1000 个查找键的哈希桶。为什么他们不能拥有一个包含 100000 个查找键的哈希桶。这与效率有关吗?

我需要您的建议,以便在我的 Web 应用程序中实现有效的方法。

附言请!不要说 stackoverflow 不是用来征求建议的,我也不知道去哪里寻求帮助。

谢谢!

最佳答案

是的,跟效率有关。

We asked the always-helpful Pieter Noordhuis, one of Redis’ core developers, for input, and he suggested we use Redis hashes. Hashes in Redis are dictionaries that are can be encoded in memory very efficiently; the Redis setting ‘hash-zipmap-max-entries’ configures the maximum number of entries a hash can have while still being encoded efficiently. We found this setting was best around 1000; any higher and the HSET commands would cause noticeable CPU activity. For more details, you can check out the zipmap source file.

小散列以特殊方式(zipmaps)编码,内存效率高,但操作复杂度为 O(N) 而不是 O(1)。因此,使用一个具有 100k 字段的 zipmap 而不是 100 个具有 1k 字段的 zipmap,您不会获得任何内存优势,但您的所有操作都会慢 100 倍。

关于python - redis - 使用哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11281734/

相关文章:

python - Python 3 中列表内容发生意外更改

python - Django 1.6 : Clear data in one table

python - 如何计算 python pandas dataframe 中的复合指标

python - Python 中用于从 Web 中提取信息的解析器

Django 表单 : editing multiple sets of related objects in a single form

mongodb - 执行时间毫秒等于 0 - MongoDB

sql - 是否有任何 API 可以使数据存储/检索变得容易?

elasticsearch - 获取最新的文档版本并汇总结果

python - ipython3 --pylab 从 csv 加载 3960 行但输出被截断

python - 如何从django模型中on_delete的SET值访问请求参数