I want to use Hashes data structure in Redis (Jedis client) but also want to maintain the insertion order something like LinkedHashMap in Java. I am totally new to Redis and gone through all the data structures and commands but somehow not able to think of any straight forward solution. Any help or suggestions will be appreciated.
Asked
Active
Viewed 1,851 times
2 Answers
0
Hashes in Redis do not maintain insertion order. You can achieve the same effect by using a Sorted Set and a counter to keep track of order. Here is a simple example (in Ruby, sorry):
items = {foo: "bar", yin: "yang", some_key: "some_value"}
items.each do |key, value|
count = redis.incr :my_hash_counter
redis.hset :my_hash, key, value
redis.zadd :my_hash_order, count, key
end
Retrieving the values in order would look something like this:
ordered_keys = redis.zrange :my_hash_order, 0, -1
ordered_hash = Hash[
ordered_keys.map {|key| [key, redis.hget(:my_hash, key)] }
]
# => {"foo"=>"bar", "yin"=>"yang", "some_key"=>"some_value"}

Carl Zulauf
- 39,378
- 2
- 34
- 47
-2
No need to use Sorted Set either counter. Just use a https://redis.io/commands#list, because it keeps the insertion order.
HSET my_hash foo bar
RPUSH my_ordered_keys foo
HSET my_hash yin yang
RPUSH my_ordered_keys yin
HSET my_hash some_key some_value
RPUSH my_ordered_keys some_key
LRANGE my_ordered_keys 0 10
1) "foo"
2) "yin"
3) "some_key"

Thomas Lehoux
- 1,158
- 9
- 13
-
This doesn't allow o(1) lookup for a given key though. – imagineerThat Feb 06 '21 at 00:26