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.

Share:
13,957

Related videos on Youtube

Joe
Author by

Joe

Updated on June 04, 2022

Comments

  • Joe
    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
    Joe over 5 years
    Thanks! Do you know about partial key match? data = r.get('123*')
  • Anna Krogager
    Anna Krogager over 5 years
    You can use r.scan(match='123*') to get a list of keys that match the given pattern, and then use mget afterwards.
  • atn
    atn about 4 years
    You should better use keys(pattern='123*') instead of scan, because to fetch all marching keys you should use scan's cursor argument and iterate till the end.