为什么 Redis 中没有有序的 hashmap?

Why there is no ordered hashmap in Redis?

Redis Data types includes sorted set 和其他用于键值存储的必要数据结构。但我想知道为什么它没有像 Java 的 TreeMap 或 C++ 的 std::map 这样的任何排序映射。我认为底层数据结构与排序集最相似,因为两者都应该是平衡的二叉搜索树。

一定有一些用例,我们必须根据键以特定顺序存储键值对。但是目前的sorted set仅仅起到了按照score存储key的作用。

There must be some use-cases where we have to store key-value pair in specific order according to key

由于Redis的键是二进制字符串,我假设你说的具体顺序是字典顺序(具体来说,键是用memcmp函数进行比较)。在那种情况下,您可以轻松地使用 SORTED SET 实现 C++ 的 std::map。您可以通过 2 个步骤实现此目的:

Build a std::set with Redis' Sorted Set

如果 SORTED SET 中的 2 个元素具有相同的分数,则它们按字典顺序排列。因此,为了构建一个 std::set,只需给一个 SORTED SET 中的所有成员提供相同的分数:

zadd std::set 0 c
zadd std::set 0 a
zadd std::set 0 b

// since all these members have the same score,
// the result is lexicographical ordered:
// a b c
zrange std::set 0 -1

// the following command will fail, since 'c' already exists.
zadd std::set 0 c

从 Redis 2.8 开始,it supports some commands 对字典范围进行操作,因此您可以构建类似于 std::set::lower_boundstd::set::upper_bound

的内容
// something similar to lower_bound: find all members not less than b
zrangebylex std::set [b +
// something similar to upper_bound: find all members greater than b
zrangebylex std::set (b +

Map each key in the set with a value

既然已经得到一个std::set,那么将key映射成一个value,就可以得到一个std::map.

set a value_a
set b value_b
set c value_c

Combine these 2 steps together

您可以将整个工作打包到一个 lua 脚本中,以获得一个 内置 std::map。并像这样使用它:

redis-cli --eval map.lua map_name , key value