Houman
Houman

Reputation: 66350

How to switch from hmset() to hset() in Redis?

I get the deprication warning, that Redis.hmset() is deprecated. Use Redis.hset() instead.

However hset() takes a third parameter and I can't figure out what name is supposed to be.

info = {'users': 10, "timestamp": datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}
r.hmset("myKey", info)

The above works, but this requires a first parameter called name.

r.hset(name, "myKey", info)

Comparing the hset vs hmset in docs isn't clear to me.

Upvotes: 14

Views: 12622

Answers (4)

ramazans
ramazans

Reputation: 41

I was using Redis.hmset() as following:

redis.hmset('myKey', info)

If you use Redis.hset() the following you will not get warning.

redis.hset('myKey', key=None, value=None, mapping=info)

With this usage, we will skip the single key & value adding step and redis.hset() will set all of the key and value mappings in info to myKey.

Upvotes: 4

David Cano
David Cano

Reputation: 151

The problem is that you must specify within hset() that you are giving it the mapping. In your case:

r.hset("myKey", mapping=info)

instead of

r.hset("myKey", info)

Upvotes: 15

chash
chash

Reputation: 4423

hmset(name, mapping): given a hash name ("myKey") and a dictionary (info) set all key/value pairs.

hset(name, key=None, value=None, mapping=None): given a hash name ("myKey") a key and a value, set the key/value. Alternatively, given a dictionary (mapping=info) set all key/value pairs in mapping.

Source: https://redis-py.readthedocs.io/en/stable/

If this does not work, perhaps you need to update the library?

Upvotes: 11

Ersoy
Ersoy

Reputation: 9594

You may execute multiple hset for each field/value pair in hmset.

r.hset('myKey', 'users', 10)
r.hset('myKey', 'timestamp', datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'))
r.hset('myKey', 'yet-another-field', 'yet-another-value')
  • first parameter is the key name
  • second parameter is the field name
  • third parameter is the value of the field.

Upvotes: 0

Related Questions