Get multiple Key/Values in Redis with Python
Asked Answered
B

3

12

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*')

Baneberry answered 16/1, 2019 at 14:6 Comment(1)
You could also have a look into other redis data types that might reflect your usecase better. For example you can store a bunch of key/values at one redis key in a redis hash and get all of them with a single r.hgetall. redis.io/topics/data-types-intro#redis-hashesFlashback
A
28

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/#)

Audy answered 16/1, 2019 at 14:12 Comment(3)
Thanks! Do you know about partial key match? data = r.get('123*')Baneberry
You can use r.scan(match='123*') to get a list of keys that match the given pattern, and then use mget afterwards.Audy
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.Functional
T
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.

Tahmosh answered 30/7, 2021 at 0:36 Comment(0)
F
0

with Django, you can directly do this that works for redis and other cache backends :

cache_results = cache.get_many(
    (
        cache_key_1,
        cache_key_2,
    )
)
cache_result_1 = cache_results.get(cache_key_1)
cache_result_2 = cache_results.get(cache_key_2)
Fairfax answered 17/6, 2022 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.