目录

  • 0x00 场景说明
  • 0x01 方法1 Redis.zadd()
  • 0x02 方法2 Redis.execute_command('ZADD', name, *pieces, **options)
  • 0x03 方法3 pipeline
  • 0x04 输出


0x00 场景说明

假设:有数条从SQL检索出的结果,需要以时间为序,存入sorted set

0x01 方法1 Redis.zadd()

import redis
import pickle  # 序列化库
import datetime

sql_rst = [
    {'sn': 'A', 'price': 2, 'dt': datetime.datetime(2020,4,24,8)},
    {'sn': 'B', 'price': 3, 'dt': datetime.datetime(2020,4,24,9)},
    {'sn': 'C', 'price': 4, 'dt': datetime.datetime(2020,4,24,10)},
]

r = redis.Redis('localhost', 6379)
params_dict = {}
for d in sql_rst:
    params_dict.setdefault(pickle.dumps(d), d.get('dt').timestamp())
r.zadd(name='tst', mapping=params_dict)

关键在于mapping参数需要是一个{member1: score1, memeber2: score2, …}的字典

0x02 方法2 Redis.execute_command(‘ZADD’, name, *pieces, **options)

import redis
import pickle  # 序列化库
import datetime

sql_rst = [
    {'sn': 'A', 'price': 2, 'dt': datetime.datetime(2020,4,24,8)},
    {'sn': 'B', 'price': 3, 'dt': datetime.datetime(2020,4,24,9)},
    {'sn': 'C', 'price': 4, 'dt': datetime.datetime(2020,4,24,10)},
]

r = redis.Redis('localhost', 6379)
params_list = []
for d in sql_rst:
    params_list.append(d.get('dt').timestamp())
    params_list.append(pickle.dumps(d))
r.execute_command('ZADD', 'tst', *params_list)

params_list是一个偶数长度的列表,偶数下标为score,奇数下标为member。(其实它就是模拟redis命令行执行zadd语句)

0x03 方法3 pipeline

import redis
import pickle  # 序列化库
import datetime

sql_rst = [
    {'sn': 'A', 'price': 2, 'dt': datetime.datetime(2020,4,24,8)},
    {'sn': 'B', 'price': 3, 'dt': datetime.datetime(2020,4,24,9)},
    {'sn': 'C', 'price': 4, 'dt': datetime.datetime(2020,4,24,10)},
]

r = redis.Redis('localhost', 6379)
pipe = r.pipeline()
for d in sql_rst:
    pipe.zadd(name='tst', mapping={pickle.dumps(d): d.get('dt').timestamp()})
pipe.execute()

0x04 输出

python redis hash 操作 python redis zadd_redis