Get multiple Key/Values in Redis with Python
13,957
Solution 1
You can use the method mget
to get the values of several keys in one call (returned in the same order as the keys):
data = r.mget(['123', '456'])
To search for keys following a specific pattern, use the scan
method:
cursor, keys = r.scan(match='123*')
data = r.mget(keys)
(Documentation: https://redis-py.readthedocs.io/en/stable/#)
Solution 2
As @atn says: (and if using django)
from django_redis import get_redis_connection
r = get_redis_connection()
data = r.keys('123*')
works now.
Related videos on Youtube
Author by
Joe
Updated on June 04, 2022Comments
-
Joe almost 2 years
I can get one Key/Value from Redis with Python in this way:
import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) data = r.get('12345')
How to get values from e.g. 2 keys at the same time (with one call)?
I tried with:
data = r.get('12345', '54321')
but that does not work..Also how to get all values based on partial key? e.g.
data = r.get('123*')
-
Joe over 5 yearsThanks! Do you know about partial key match?
data = r.get('123*'
) -
Anna Krogager over 5 yearsYou can use
r.scan(match='123*')
to get a list of keys that match the given pattern, and then use mget afterwards. -
atn about 4 yearsYou should better use
keys(pattern='123*')
instead ofscan
, because to fetch all marching keys you should use scan'scursor
argument and iterate till the end.