Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get multiple Key/Values in Redis with Python

Tags:

python

redis

get

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

like image 560
Joe Avatar asked Jan 16 '19 14:01

Joe


People also ask

How do I get multiple keys in Redis?

You already can retrieve multiple keys, but not arbitrary ones. If your primary goal is to retrieve multiple arbitrary keys, use a hash and hmget. If your primary need is to access a sorted set, use sorted set and either go the scripting route or pipeline a series of zscore calls.

Can Redis key have multiple values?

Redis Lists In Redis you can also have lists as the value, which overcomes the problem of having more than one value for a key, as you can have an ordered list with multiple values (so “they'll none of 'em be missed”).

How do I query Redis in Python?

Using Redis-Py package. Create a Python file and add the code shown below to connect to the Redis cluster. Once we have a connection to the server, we can start performing operations. The above example will connect to the database at index 10. The line above will take the first arguments as key and value, respectively.


2 Answers

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

like image 80
Anna Krogager Avatar answered Sep 20 '22 23:09

Anna Krogager


As @atn says: (and if using django)

from django_redis import get_redis_connection

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

works now.

like image 22
Tim Richardson Avatar answered Sep 21 '22 23:09

Tim Richardson