Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashMap behaviour with Redis Hashes?

Tags:

redis

jedis

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.

like image 818
Ashu Avatar asked Aug 22 '26 06:08

Ashu


1 Answers

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"}
like image 57
Carl Zulauf Avatar answered Aug 24 '26 21:08

Carl Zulauf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!