Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REDIS Error: WRONGTYPE Operation against a key holding the wrong kind of value

When I store an object to Redis like this, it works fine

payload = {'age': 12}
key = 'animals:cow'
r.hmset(key, payload)

However when I create the key by joining 2 strings

payload = {'age': 12}
key = 'animals:' + 'cow'
r.hmset(key, payload)

I get the error

redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value

Why is the second example giving an error when the key string is the same as in the first example?

like image 745
Nyxynyx Avatar asked Nov 08 '22 12:11

Nyxynyx


1 Answers

I can't replicate your issue. Maybe you're mixing string & hash methods? Here's my environment:

  • Python 3.6.5
  • Redis stable 5.0.5

I used your exact code, but I added this above:

from redis import StrictRedis
r = StrictRedis(host="localhost", port=6379, db=0)

-Your code works for me!
-Maybe you used a different set method before hmset?
-Redis is more than a plain key-value store; in traditional key-value stores we associate string keys to string values. However, Redis gives us some additional options, and incompatabilities between these can cause errors. https://redis.io/topics/data-types-intro
-Unless you had hidden characters or special unicode versions of things that were not the same, there is no difference between #1 and #2:
1. key = 'animals:cow'
2. key = 'animals:' + 'cow'

It's possible you've got a type-conflict going on with Redis due to elements in your code you have not shared; i.e. maybe you set one way, then attempted to set another way. There's many ways to set values in Redis. Errors happen if we set one way, then another (with different methods). Here's some examples of how you can set keys & values in Redis:

  • if value is of type string -> SET <key> <value>
  • if value is of type string -> MSET <key> <value> [key value ...]
  • if value is of type hash -> HSET <key> <field> <value>
  • if value is of type hash -> HMSET <key> <field> <value> [field value ...]
  • if value is of type lists -> SETRANGE <key> <offset> <value>
  • if value is of type binary -> SETBIT <key> <offset> <value>

A related problem when trying to get things that were set different ways: WRONGTYPE Operation against a key holding the wrong kind of value php

like image 78
Jason F Avatar answered Nov 14 '22 20:11

Jason F