Redis中的字典列表

10
如何使用Python-redis将字典列表存储在Redis中的一个键上。以下是我想要实现的数据结构:
'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'}],
}

我想将会话列表添加到现有列表中,同时添加新的会话并检索它们。如何使用Python-redis实现这一点?

2个回答

13

使用picklejson将您的字典 {'image': 'image-url', 'url' : 'url', 'title' : 'test_title', 'description' : 'test_description'} 序列化为字符串,并将它们存储到 Redis 列表中。 使用类似于 browsing_history:SESSION_KEY_1 的键来访问这些列表。 如果您需要获取所有会话密钥的列表,则可能需要维护一组键字符串 browsing_history:*


这看起来很有趣,但我担心读取和迭代。通过这个列表进行迭代需要对每个项目进行反序列化。在这种方法论下,添加操作是快速的。 - Tommy
在将数据从任何来源加载到Python对象中时,反序列化步骤始终是必需的。大多数数据库驱动程序会为您执行此操作,因此通常不可见。 - Ski

4
一种不需要序列化和不受字符串大小限制(但不一定更高效)的解决方案是将每个字典存储在自己专用的哈希映射表中:
# 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]) 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接