GAL
GAL

Reputation: 39

How should I use redis?

I'm doing an api in laravel and I want to use Redis. I'm not sure if I'm doing well.

How should I use Redis to store json and then get a value by ID or another column. Should I save the json as plain text? Then how do I go through it to look for a specific value or how you should keep the values?

     {
        "id": 1,
        "name": "Package A",
        "dimensions": "100x100x100",
        "created_at": "2019-05-29 01:35:53",
        "updated_at": "2019-05-29 01:35:53"
    },
    {
        "id": 2,
        "name": "Package B",
        "dimensions": "150x150x150",
        "created_at": "2019-05-29 01:36:53",
        "updated_at": "2019-05-29 01:36:53"
    }

$package = Package::where->get();
Redis::hmset('packages', array($package));

Or I shoud ..

$package = Package::where->get();
Redis::set('packages', serialize($package));

Then How I get a value? For example: all fields id=2

Upvotes: 0

Views: 185

Answers (1)

Sergio Kaznowiecki
Sergio Kaznowiecki

Reputation: 36

I recommend saving the information in the following way, so it is easier to access later.

Package::all()->each(function($package){
   Redis::set("package:{$package->id}", $package->toJson());
});

And if you need to recover information :

json_decode(Redis::get("package:$id"), true);

In redis you have to consider how to access the information, and then how to save it. For example, if you want to search by name, your key will be composed of the same name.

If you want retrive all packages from Redis, you will need all of packages key´s.

The folowing command retrive all keys matches with the structure :

Redis::keys('package:*');

After that, you can do the following

$keys = Redis::keys('package:*');
$packages = [];
foreach ($keys as $key){
    array_push($packages, json_decode(Redis::get($key), true));
}
return $packages;

Upvotes: 1

Related Questions