Joe
Joe

Reputation: 13131

Get multiple Key/Values in Redis with Python

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

Upvotes: 12

Views: 27462

Answers (3)

Laurent Lyaudet
Laurent Lyaudet

Reputation: 968

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)

Upvotes: 0

Anna Krogager
Anna Krogager

Reputation: 3588

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

Upvotes: 29

Tim Richardson
Tim Richardson

Reputation: 7251

As @atn says: (and if using django)

from django_redis import get_redis_connection

r = get_redis_connection()
data = r.keys('123*')

works now.

Upvotes: 2

Related Questions