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

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-hashes Commented Jan 16, 2019 at 17:17

3 Answers 3

30

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Do you know about partial key match? data = r.get('123*')
You can use r.scan(match='123*') to get a list of keys that match the given pattern, and then use mget afterwards.
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.
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.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.