WRONGTYPE Operation against a key holding the wrong kind of value php
PhpRedisPhp Problem Overview
Hi I am using Laravel with Redis .When I am trying to access a key by get method then get following error "WRONGTYPE Operation against a key holding the wrong kind of value"
I am using following code to access the key value -
i use this code for get data from redis
$values = "l_messages";
$value = $redis->HGETALL($values);
print($value);
Php Solutions
Solution 1 - Php
Redis supports 6 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
- if value is of type string -> GET
<key>
- if value is of type hash -> HGETALL
<key>
- if value is of type lists -> lrange
<key> <start> <end>
- if value is of type sets -> smembers
<key>
- if value is of type sorted sets -> ZRANGEBYSCORE
<key> <min> <max>
- if value is of type stream -> xread count
<count>
streams<key>
<ID>
. https://redis.io/commands/xread
Use the TYPE
command to check the type of value a key is mapping to:
- type
<key>
Solution 2 - Php
This error means that the value indexed by the key "l_messages" is not of type hash
, but rather something else. You've probably set it to that other value earlier in your code. Try various other value-getter commands, starting with GET, to see which one works and you'll know what type is actually here.
Solution 3 - Php
This error says that you are trying to push a wrong value into the key, which means that there already exists same key but with different data structure.
To get all the keys do this in the redis cli
keys *
This should display all the keys Now to get the type of value the key stores, do
type <key>
so it says what value you can push into the key. In my case the type was string (using set) and i was trying to use the key as list
Solution 4 - Php
I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like
$redis->set('persons', $persons)
Later I decided to change to "hSet" method, and I tried it this way
foreach($persons as $person){
$redis->hSet('persons', $person->id, $person);
}
Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with
del persons
It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.
Solution 5 - Php
Sometimes it's because you are in a wrong db number. I had a same problem and changed the db to the right one, there was no problem and it worked!. I suggest you before HGETALL or whatever you want, select the correct db or at least considering which db you are in.