Shabin Hashim
Shabin Hashim

Reputation: 707

Redis storing list inside hash

I have to store some machine details in redis. As there are many different machines i am planning to use the below structure

server1 => {name => s1, cpu=>80}
server2 => {name => s2, cpu=>40}

I need to store more than one value against the key CPU. Also i need to maintain only the last 10 values in the list of values against cpu

1) How can i store a list against the key inside the hash?

2) I read about ltrim. But it accepts a key. How can i do a ltrim for key cpu inside server1?

I am using jedis.

Upvotes: 35

Views: 33758

Answers (3)

Nikita Koksharov
Nikita Koksharov

Reputation: 10803

It's possible to do this with Redisson framework. It allows to store a reference to Redis object in another Redis object though special reference objects which handled by Redisson.

So your task could be solved using List inside Map:

RMap<String, RList<Option>> settings = redisson.getMap("settings");

RList<Option> options1 = redisson.getList("settings_server1_option");
options1.add(new Option("name", "s1"));
options1.add(new Option("cpu", "80"));
settings.put("server1", options1);

RList<Option> options2 = redisson.getList("settings_server2_option");
options2.add(new Option("name", "s2"));
options2.add(new Option("cpu", "40"));
settings.put("server2", options2);

// read it
RList<Option> options2Value = settings.get("server2");

Or using Map inside Map:

RMap<String, RMap<String, String>> settings = redisson.getMap("settings");

RMap<String, String> options1 = redisson.getMap("settings_server1_option");
options1.put("name", "s1");
options1.put("cpu", "80");
settings.put("server1", options1);

RMap<String, String> options2 = redisson.getMap("settings_server2_option");
options2.put("name", "s2");
options2.put("cpu", "40");
settings.put("server2", options1);

// read it
RMap<String, String> options2Value = settings.get("server2");

Diclamer: I'm a developer of Redisson

Upvotes: 8

Mohankumar M
Mohankumar M

Reputation: 111

You can encode/stringify push the data, while pulling data you can decode/parse the data.

Encode -> Decode

Stringify -> Parse

Upvotes: 5

Itamar Haber
Itamar Haber

Reputation: 50102

Redis' data structures cannot be nested inside other data structures, so storing a List inside a Hash is not possible. Instead, use different keys for your servers' CPU values (e.g. server1:cpu).

Upvotes: 39

Related Questions