Home > Software design >  How to get all HMSET - Laravel Redis
How to get all HMSET - Laravel Redis

Time:06-09

Hmset Example Screenshot

This is my demo hmset example, I try to get all hmset list by Redis::hgetall("hmset_demo:user_id:*"), but it return a empty array [].

How can I get this return:

[{
    "id": "1",
    "name": "name edited 1",
    "description": "desc edited 1",
    "avatar": "xxx 1"
},
{
    "id": "1",
    "name": "name edited 1",
    "description": "desc edited 1",
    "avatar": "xxx 1"
},
...
]

PS: I use the following code to insert:

Redis::hmset("hmset_demo:user_id:".$id, [
            'id'    =>  $id,
            'name'    =>  'name edited '.$id,
            'description'    =>  'desc edited'.$id,
            'avatar'    =>  'xxx'.$id,
        ]);

I can get specific hmset data by this code:

$id = 1;
Redis::hgetall("hmset_demo:user_id:".$id);

CodePudding user response:

You cannot use wildcards in key names.

Let's see an example. We store two hash type keys

127.0.0.1:6379> HSET hmset_demo:user_id:0 NAME PETER
127.0.0.1:6379> HSET hmset_demo:user_id:1 NAME GWEN

We can retrieve their value by its key

127.0.0.1:6379> HGETALL hmset_demo:user_id:0
1) "NAME"
2) "PETER"

127.0.0.1:6379> HGETALL hmset_demo:user_id:1
1) "NAME"
2) "GWEN"

But we cannot use wildcards with HGETALL command

127.0.0.1:6379> HGETALL hmset_demo:user_id:*
(empty array)

If you need to use wildcards to retrieve a lot of keys, you can use SCAN COMMAND

127.0.0.1:6379> SCAN 0 MATCH hmset_demo:user_id:* COUNT 10
1) "0"
2) 1) "hmset_demo:user_id:1"
   2) "hmset_demo:user_id:0"

Iterate each element from the resulset and retrieve its values using HGETALL

There is no way to retrieve everything using just one Redis command

Also, HMSET command is deprecated. You should use HSET instead.

  • Related