0

I have several Mountain objects which have id and name.

I stored these objects like that

HMSET Mountain:1 id "1" name "Mo1"
HMSET Mountain:2 id "2" name "Mo2"
HMSET Mountain:3 id "3" name "Mo2"

How can I get all Mountain Objects? Or are there any better way storing objects in redis?

maskapsiz
  • 244
  • 5
  • 23

1 Answers1

3

You should do it with 2 command :

KEYS Mountain:*
HGETALL <everykeys>

But , if you can, it's better to not use KEYS command , so you can do something like this :

HMSET Mountain:1 id "1" name "Mo1"
SADD Montains Mountain:1
HMSET Mountain:2 id "2" name "Mo2"
SADD Montains Mountain:2
HMSET Mountain:3 id "3" name "Mo3"
SADD Montains Mountain:3

and get it :

SMEMBERS Mountain
HGETALL <everykeys>

Redis is a key/value system with extra data type, so you have to build your index So for having a name indexing for example, if name are unique:

HSET Mountains:IdByName "Mo3" 3

and you will get the id :

HGET Mountains:IdByName "Mo3"

for non unique lets use set again

SADD Mountains:IdByName:Mo3 3

And you will increase the number of keys and that why KEYS is not recommend , because to expensive

next step is use a lua script for having/setting hash from/and index

Philippe T.
  • 1,182
  • 7
  • 11
  • Ok. I understand concept. Are there any way get Mountain which name is "Mo2"? – maskapsiz Jul 08 '14 at 11:46
  • redis have some more complex data type then classic key/value but not enought for thid. you have to create you own . i put it in answer , that quite usefull – Philippe T. Jul 08 '14 at 12:37