Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis, how to store sets as the values of hash key

Tags:

redis

I've seen questions on how to create an array of hash objects in Redis. But I want another arrangement: a Hash object, whose fields are Strings and values are Sets.

Should I create the sets separately from the Hash? If so, how would I reference that set? Through the variable name?

Can I manipulate them from a higher level, ie: sadd Hash_name.field_name append_this_value_to_set ?

Furthermore, how would I read those inner Sets?

like image 582
Rafael Avatar asked Jun 26 '15 06:06

Rafael


2 Answers

Redis doesn't provide nested data structures, therefore a Hash field's value can't be a Set and can only be a String.

One way of doing something similar to what the OP is trying to achieve is to use regular Sets and store their key names in the Hash's values. Dereferencing these, however, requires performing the additional operations in code.

like image 175
Itamar Haber Avatar answered Sep 25 '22 10:09

Itamar Haber


For example, you may create a set named user which contains all user ids in the system, and a set named asset which contains all assets in the company.

> sadd user 1000 1001 1002 1003
(integer) 4
> type user
set

> sadd asset 20190001 20190002 20190003
(integer) 3
> type asset
set

Then use hashes to describe each user and asset record.

> hmset asset:20190001 desc laptop price 2000
OK
> hmset asset:20190002 desc pc price 1800
OK
> hmset asset:20190003 desc laptop price 2100
OK
> hmset asset:20190004 desc laptop price 2000
OK

A user could hold more than one asset.

> hmset user:1000 username Samuel birthyear 1980 asset 20190001:20190002
OK
> hmset user:1001 username David birthyear 1984 asset -1
OK
> hmset user:1002 username Marry birthyear 1987 asset 20190004
OK
> hmset user:1003 username Joe birthyear 1977 asset 20190003

Use your code to implement the logic.

like image 44
yoonghm Avatar answered Sep 24 '22 10:09

yoonghm