NLP | Storing an ordered dictionary in Redis



 

class RedisOrderedDict (collections.MutableMapping):

  

  def __ init__ ( self , r, name):

self ._ r = r

self ._name = encode_key (name)

  

def __ iter __ ( self ):

return iter ( self . items ())

 

def __ len __ ( self ):

return self ._r.zcard ( self ._ name)

 

  def __ getitem __ ( self , key):

return self ._ r.zscore ( self . _name, encode_key (key))

 

  def __ setitem __ ( self , key, score):

self ._r.zadd ( self ._ name, encode_key (key), score)

 

def __ delitem __ ( self , key):

self ._ r.zrem ( self ._ name, e ncode_key (key))

 

def keys ( self , start = 0 , end = - 1 ):

# we use zrevrange to sort keys

  # by value instead of

lowest

return self ._ r.zrevrange ( self ._ name, start, end)

  

def values ​​( self , start = 0 , end = - 1 ):

return [v for (k, v) in self . items (start = start, end = end)]

 

def items ( self , start = 0 , end = - 1 ):

  return self ._ r.zrevrange ( self ._ name, start, end, withscores = True )

  

  def get ( self , key, default = 0 ):

return self [key] or default

 

def iteritems ( self ):

return iter ( self )

 

def clear ( self ):

  self ._ r.delete ( self ._ name)

Code: Create a RedisOrderedDict instance by passing a Redis connection and unique name

Exit :

 0 5.2000000000000002 1 [(b`bar`, 5.2)] 

Most of the code might look similar to RedisHashMap, which is to be expected since they both extend collections . The main difference is that RedisOrderedSet orders keys by floating point values, and therefore is not suitable for arbitrary storage of key values ​​such as RedisHashMap
Sketches explaining each key method and how they work with Redis:

  • __len __ (): the zcard command is used to get the number of items in an ordered set.
  • __getitem __ (): uses the zscore command to get the score for a key and returns 0 if the key does not exist.
  • __ setitem __ (): this command uses the zadd command to add a key to the ordered set with a given score, or update the score if the key already exists.
  • __delitem __ (): The zrem command is used to remove a key from the ordered set.
  • keys (): The zrevrange command is used to get all the keys in the ordered set sorted by the highest score. To get a snippet of ordered keys more efficiently requires two optional keyword arguments, start and end.

from redis import Redis

from rediscollections import RedisOrderedDict

 

r = Redis ()

rod = RedisOrderedDict (r, `test` )

rod.get ( ` bar` )

  

rod [ `bar` ] = 5.2

print (rod [ `bar` ])

 

print ( len (rod))

 

print (rod.items ()) 

 
rod.clear ()