Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Dicts in Redis

Tags:

python

redis

How to keep a list of dicts in Redis against a key using Python-redis. The following is the data structure which I am aiming at:

'browsing_history' : {
    'session_key_1' : [{'image': 'image-url', 'url' : 'url', 'title' : 'test_title', 'description' : 'test_description'}, {''image': 'image-url2', 'url' : 'url2', 'title' : 'test_title2', 'description' : 'test_description2'}],
    'session_key_2' : [{'image': 'image-url', 'url' : 'url', 'title' : 'test_title', 'description' : 'test_description'}, {''image': 'image-url2', 'url' : 'url2', 'title' : 'test_title2', 'description' : 'test_description2'}],
}

Would like to add into the session lists as well as add new sessions and also retrive them. How can I do this using Python-redis?

like image 854
Siddharth Avatar asked Dec 29 '11 06:12

Siddharth


People also ask

Can you store dictionary in Redis?

Use json to make a string representation of the dictionary, then store it as a value in the Redis database.

What is Redis StrictRedis?

source code object --+ | StrictRedis. Implementation of the Redis protocol. This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol. Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server. Instance ...

Can Redis store nested objects?

Storing the object in two hash tables. Since hash tables in Redis can not be nested (a.k.a. need to be “flat”), you have to use two hash tables in order to store the house-object.


2 Answers

Serialize your dictionary {'image': 'image-url', 'url' : 'url', 'title' : 'test_title', 'description' : 'test_description'} with pickle or json. Use redis list to store them as strings. Use keys like browsing_history:SESSION_KEY_1 to access those lists. If you need to get a list of all session keys you probably will need to maintain a set of strings for keys browsing_history:*.

like image 94
Ski Avatar answered Sep 23 '22 13:09

Ski


A solution not requiring serialization and not restricted by the limits on string sizes (but not necessarily more performant) is to store each dict in its own dedicated hash map:

# define root name for hashes used 
# to store list elements - dicts
hash_root_name='test_hash'

# sample list of dicts
dicts_list=[test_dict1, test_dict2]

# store dicts from the list to consecutively 
# named redis hashes,  with list indices 
# appended to hash root name
for i in range(len(dicts_list)):
    
    redis_client.hmset(hash_root_name+str(i), 
                       dicts_list[i]) 

like image 44
mirekphd Avatar answered Sep 22 '22 13:09

mirekphd