LinkedHashMap behavior with Redis hashes?

I want to use hash data structure in Redis (Jedis client), but also want to maintain insert order, like LinkedHashMap in Java. I'm completely new to Redis and have gone through all the data structures and commands, but somehow couldn't come up with any direct solution. Any help or suggestions would be appreciated.

+3


source to share


1 answer


Hashes in Redis don't support insertion order. You can achieve the same effect using a Sorted Set and a counter to keep track of the order. Here's 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

      



Getting the values ​​in order will 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"}

      

0


source







All Articles